(Original Article at http://sgdev-blog.blogspot.sg/2014/01/css-score.html)
We all know that when many conflict css properties can be applied for one web element, it is by specification that the more specific properties will be applied. However, specific is an abstract word. Hence, it is better that we know about css score, or how browser choose which properties to override.
Browser categorize css to 4 categories with the specificity from high to low as:
1/ Style Attribute:
2/ ID: #some_id{ color: red;}
3/ Class, pseudo class, attribute: .some_class {color:green;}
4/ Elements: li {color:black;}
From W3C recommendation, the result of this calculation takes the form of four comma-separated values, a,b,c,d,1 where the values in column “a” are the most important and those in column “d” are least important. A selector’s specificity is calculated as follows:
To calculate a, count 1 if the declaration is from a style attribute rather than a rule with a selector (an inline style), 0 otherwise.
To calculate b, count the number of ID attributes in the selector.
To calculate c, count the number of other attributes and pseudo-classes in the selector.
To calculate d, count the number of element names and pseudo-elements in the selector.
Here is one example using this rule:
body#home div#warning p.message --> 0, 2, 1, 3
Please notice the comma ',' in the css score, it is there to remind us that the score b, c, d can be equal or bigger than 10. Still, the rule to compare is left to right.
We all know that when many conflict css properties can be applied for one web element, it is by specification that the more specific properties will be applied. However, specific is an abstract word. Hence, it is better that we know about css score, or how browser choose which properties to override.
Browser categorize css to 4 categories with the specificity from high to low as:
1/ Style Attribute:
2/ ID: #some_id{ color: red;}
3/ Class, pseudo class, attribute: .some_class {color:green;}
4/ Elements: li {color:black;}
From W3C recommendation, the result of this calculation takes the form of four comma-separated values, a,b,c,d,1 where the values in column “a” are the most important and those in column “d” are least important. A selector’s specificity is calculated as follows:
To calculate a, count 1 if the declaration is from a style attribute rather than a rule with a selector (an inline style), 0 otherwise.
To calculate b, count the number of ID attributes in the selector.
To calculate c, count the number of other attributes and pseudo-classes in the selector.
To calculate d, count the number of element names and pseudo-elements in the selector.
Here is one example using this rule:
body#home div#warning p.message --> 0, 2, 1, 3
Please notice the comma ',' in the css score, it is there to remind us that the score b, c, d can be equal or bigger than 10. Still, the rule to compare is left to right.