Isaac.

CSS Specificity

Understanding CSS Specificity

CSS Specificity is a crucial concept in understanding how browsers decide which styles to apply when multiple CSS rules target the same HTML element. It's essentially an algorithm that calculates the "weight" or relevance of a selector. The selector with the highest specificity score wins, and its styles are applied.

How Specificity is Calculated

Specificity is calculated based on the types of selectors used in a CSS rule. It's often represented as a four-part value, typically in the format of ID - CLASS - TYPE.

  • Inline Styles: Applied directly to an element using the style attribute. Specificity: (1,0,0,0).
  • ID Selectors: #my-id adds (1,0,0).
  • Class, Attribute, and Pseudo-classes: (.my-class, [type="text"], :hover) each add (0,1,0).
  • Type Selectors and Pseudo-elements: (p, ::before) each add (0,0,1).
  • Universal Selector and Combinators: *, +, >, ~ add nothing.

Note: pseudo-classes like :is(), :has(), and :not() themselves don't add specificity, but their contents do.

Specificity Hierarchy and Ties

  1. ID selectors outweigh class and type selectors.
  2. If ID counts are equal, class/attribute/pseudo-class selectors win.
  3. If those are equal, type/pseudo-element selectors decide.

If two selectors have the exact same specificity, the later rule in the stylesheet wins. The !important rule overrides all specificity but should be used sparingly.

Example

Let's consider an <h1> element with these rules:

<h1 id="main-title" class="section-heading">Hello World</h1>
h1 {
  color: blue; (0,0,1)
}

.section-heading {
  color: green; (0,1,0)
}

#main-title {
  color: red; (1,0,0)
}

#main-title.section-heading {
  color: purple; (1,1,0)
}

The <h1> will be purple because the last rule has the highest specificity (1,1,0).

Overriding Specificity

1. Increasing Specificity

Write a selector with a higher specificity than the one you want to override. For example:

p {
  color: blue;
}

.content p {
  color: green;
}

2. Using !important

The !important declaration overrides all specificity rules:

p {
  color: blue !important;
}

3. Source Order

When two rules have the same specificity, the later one wins:

.box {
  color: red;
}

.box {
  color: blue;
}

4. Inline Styles

Inline styles have the highest specificity and can only be overridden by !important.

<p style="color: blue;">This text is blue.</p>
p {
  color: red !important;
}