20 August 2023
I had a colleague who had been in the industry for years but had no idea what CSS specificity is. This is one of those things that you actually do for so long without realizing there's a term for it and how it actually works.
HTML
CSS
In the code above, what will be the text color of the <p>
tag?
Do you know why it's #p1
rule gets applied and not the other CSS rules?
It's because of theĀ CSS Specificity.
You can think of it as the score/points that determines which CSS rule will be applied to the target element. The more specific a rule, the more likely it is to be applied. Each type of selector has specificity value.
The table below shows the specificity of each type of selector:
Selector | Specificity |
---|---|
Inline Style | 1000 |
ID | 100 |
Class | 10 |
Element | 1 |
Attribute | 1 |
Check the table below for the specificity value of each CSS rules we used in our first short quiz above.
CSS Rule | Specificity |
---|---|
p {...} | 1 |
#p1 {...} | 100 |
.red {...} | 1 |
And #p1
has the highest value among the 3 rules, hence overwriting the other CSS rules.
Let's practice more. Try to answer what CSS rule will be applied in the example below:
HTML
CSS
Which rule will be applied?
Both selectors has specificity value of 10 but the .yellow
CSS rule is declared after the .red
. If selectors has the same specificity value, the CSS rule that applied "latest" will be applied.
Let's try another one!
HTML
CSS
Which CSS rule has the highest specificity value and will be applied?
Check the table below for the specificity value for each CSS rules we used on the code above:
CSS Rule | Specificity |
---|---|
.red {...} | 10 |
.yellow {...} | 10 |
#div .green {...} | 110 |
#div p {...} | 101 |
Understanding how CSS Specificity works can help you in many ways such as:
Avoid conflicts between CSS rules. Multiple rules can be confusing. Understanding how the specificity works can help you to make clearer rules and fewer lines of code.
Debugging CSS problems. Knowing which rules are being applied to a problem element can help you identify the source of the problem.
Overwriting 3rd-Party styling. This is my favorite reason why understanding CSS Specificity is a must. It's very common to use third-party scripts that come with their own styling, and we want to minimize the changes we make to get our desired styling.
There are still a lot of things that I didnt cover in this article, such as !important
rule and examples for inline styles. I hope this article gives you a boost to learn more about CSS specificity related topics.
Learn more