I know it may sound strange but a lot of developers and engineers still find it difficult to get their way around CSS3 Specificity. If you have doubts of why this color isn't working or why your font isn't responding to your defined styles set then you have no more reason for doubts, join me as we unveil the secret recipes to handling css3 specificity.
What is CSS Specificity?
According to MDN
Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors
In other words it is just a rule-set that web browsers uses to decide which css property with higher priority to add on a given element or selectors that matched it.
How can one calculate specificity?
There are many ways to calculate specificity but I will be showing you the easiest method, it is called the ABCD method.
A represent style attribute or inline style, which carries the highest priority
B represent the id selector that carries the second highest priority when applied on an element
C represent classes, pseudo elements and attribute
D represent elements
From the above description you will understand that A have the value of 1000, while B have the value of 100, also C have the value of 10, and D have the value of 1.
If only A is applied on an element, it will look like this:
A = 1
B = 0
C = 0
D = 0
And if B is applied on an element, it will look like this:
A = 0
B = 1
C = 0
D = 0
If C is also applied on an element, it will look like this:
A = 0
B = 0
C = 1
D = 0
And if D is applied on an element. it will look like this:
A = 0
B = 0
C = 0
D = 1
Right now looking at the diagram above, I think you have grasp the concept and if you continue practicing and adding each method together open up your mind to endless possibility or understanding.
Let me know what you think by leaving a comment.
Top comments (2)
Well, that's the very basics. The next steps are explain that the 1,10,100,1000 values are in an effectively infinite number base. Also you could include how to count the special case of the :not() pseudo-class. Braver is to explain why specificity, designed the way it is, is helpful, which requires an understanding of how selectors couple the styling of CSS properties to the semantics of the markup language.
Finally, technically what you have described is not css3 specificity, but css2 specificity. The Level 3 Selectors specification deliberately omits the style attribute value because it is an HTML feature, not a CSS one. The HTML style attribute can be regarded as simply something that trumps CSS specificity, rather than being part of it.
Thanks for your review and your suggestions.
I will try to update this article.