Understanding CSS Specificity

Today

What is CSS Specificity?

Imagine you have a box of toys, and you want to decide which toy to play with. Some toys are your favorites, some are okay, and others are at the bottom of the box. You’ll always pick your favorite first. CSS specificity works like this—it helps the browser decide which style to use when multiple rules are applied to the same element.

Why Does Specificity Matter?

Sometimes, more than one CSS rule tries to style the same element. Specificity is like a score that helps the browser figure out which rule is the most important.

For example:

<p class="highlight" id="special">This is a paragraph.</p>

And the CSS:

p {
  color: green;
}
 
.highlight {
  color: blue;
}
 
#special {
  color: red;
}

Which color will the text be? Red! Why? Because the rule with #special (an ID) is more specific than the others.


Specificity Score: How Does It Work?

Specificity is like a points system. The browser looks at the types of selectors in a rule and assigns points:

  1. Inline styles (e.g., style="color: red;") get 1000 points.
  2. IDs (e.g., #special) get 100 points.
  3. Classes, attributes, and pseudo-classes (e.g., .highlight, [type="text"], :hover) get 10 points.
  4. Elements and pseudo-elements (e.g., p, h1, ::before) get 1 point.

Example of Scoring:

/* Rule 1 */
#special .highlight p {
  color: blue;
}
/* Rule 2 */
.highlight p {
  color: green;
}
/* Rule 3 */
p {
  color: yellow;
}

The highest score wins, so Rule 1 applies, and the text is blue.


Specificity in Real Life

Let’s say you’re building a website with a button. Here’s the HTML:

<button class="btn" id="submit">Click Me</button>

And the CSS:

button {
  background-color: gray;
}
 
.btn {
  background-color: blue;
}
 
#submit {
  background-color: green;
}

The green background from #submit is applied because it has the highest specificity.


What Happens When Scores Are Equal?

If two rules have the same specificity, the browser will apply the one that comes last in the CSS file.

Example:

p {
  color: blue;
}
 
p {
  color: red;
}

The text will be red because the second rule comes later.


How to Avoid Specificity Issues

  1. Use Classes Instead of IDs: Classes are reusable, while IDs are unique. Using IDs can make your CSS harder to manage.

  2. Avoid Inline Styles: Inline styles have the highest specificity, but they’re difficult to maintain and debug.

  3. Keep Selectors Simple: Avoid overly complicated selectors like div > ul > li:first-child > a. They can cause unnecessary specificity battles.

  4. Use !important Sparingly: Adding !important to a rule forces it to apply, but overusing it can make your stylesheets messy and hard to debug.


Conclusion

CSS specificity is like a game of importance. The browser decides which rule to apply based on scores, and the rule with the highest score wins. By understanding and using specificity wisely, you can write clean and predictable CSS.