Have you ever thought of how CSS rules are rendered by browsers? How do browsers define which CSS rules have higher priority? Beginning web developers sooner or later come to the question of CSS Specificity. Just imagine your CSS file has the following lines:
p {color:white;}
p {color:red;}
How should browsers render this code? There must be some way to determine the importance of this or that line. And this way exists – it’s called CSS Specificity.
Let’s calculate specificity
A simple example. Your HTML file contains a text layer with class “about-me”. You CSS file have the following CSS rules:
div {font-weight: normal;}
div.about-me {font-weight: bold;}
It’s not hard to guess that the text in the DIV would be in a bold font. Why? Because the second rule is more specific than the first rule. But how can one know for sure which rule is more specific?
In fact there are exact formulas to calculate CSS specificity. Browsers use these formula, and it will be helpful if you know it. Every aspect of an element has a numerical value. So the formula is:
SPECIFICITY (a,b,c,d)
- Element, Pseudo Element: d = 1 – (0,0,0,1)
- Class, Pseudo class, Attribute: c = 1 – (0,0,1,0)
- Id: b = 1 – (0,1,0,0)
- Inline Style: a = 1 – (1,0,0,0)
And now a short example to demonstrate how it works.
div [just 1 element, the specificity is (0,0,0,1)]
strong [just 1 element, the specificity is (0,0,0,1)]
div.about-me [1 element with 1 class, the specificity is (0,0,1,1)]
div.about-me span strong [3 elements with 1 class, the specificity is (0,0,1,3)]
div.about-me span#more strong [3 elements with 1 class and 1 ID, the specificity is (0,1,1,3)]
It’s very important to understand that a rule with the specificity of (0,0,0,99) is less important than (0,0,1,0).
Sometimes you need to create a rule that is super-important. You could perhaps make a rule with specificity of (1,9,9,9), however there is an easier way: you just need to add ‘!important’ (without quotes), i.e. this rule is super-important:
div {color:#FFF !important;}
One more recommendation – spend some hours on CSS analysis. Check how well-known portals use CSS techniques – you will be surprised how many solutions are used by professionals to make cross-browser beautiful websites.
