Site icon WebDevStudios

CSS Specificity: What You May Not Have Known

Most front-end developers glaze over at the mention of the word. However, having a strong grasp of how CSS Specificity works is key to minimizing tedious debugging. Specificity tells the browser what rules to apply to an element, and if there is a conflict then the higher priority wins.

Let’s look at some simple examples, and put this concept into context.

Pop Quiz – Question #1: Rule Order

[snippet slug=class-vs-class line_numbers=false lang=html][snippet slug=class-vs-class-css line_numbers=false lang=cs]

What is the background-color of the <div> based on the example above?

If you answered blue, you are correct.

Since the declaration comes later in the CSS (near the bottom), it has a higher specificity. This is fundamentally the simplest rule of the cascade in Cascading Style Sheets (CSS). If there is a conflict in rules (e.g. background-color: blue vs background-color: red), and since the classes have the same weight, then the cascade wins.

A similar scenario is the following:

[snippet slug=css-rule-order-html line_numbers=false lang=html][snippet slug=css-rule-order-css line_numbers=false lang=cs]

Again, the same outcome, because background-color: blue comes later in the declaration block.

Ok, that was easy. Now let’s try one that’s a little harder:

Pop Quiz – Question #2: Pseudo-element vs Pseudo-class

[snippet slug=pseudo-element-vs-pseudo-class-hmtl line_numbers=false lang=html][snippet slug=pseudo-element-vs-pseudo-class-css line_numbers=false lang=cs]

What color will the text be?

This time red wins. The h1::first-line pseudo-element has higher specificity than the h1:first-child pseudo-class. Here is how we can calculate and know for sure:

Calculating Specificity

Here are the rules for calculating specificity, as outlined by W3C:

[snippet slug=calculating-specificity-examples lang=cs]

So let’s calculate and compare the Specificity of the example (Pop Quiz – Question #2: Pseudo-element vs Pseudo-class) up above to verify our answer was correct.

[snippet slug=pseudo-element-vs-pseudo-class-calculate-specificity lang=cs]

A Few Special Rules

Conclusions

Basically, only be as specific as you need to be. Being too specific mostly makes it harder to override things further down the line.

Tools & Further Reading

Exit mobile version