Thursday 6 October 2005
LEST YOU GET SWEPT UP into the stars with the imaginative Malarkey, who puts a cleverly galactic twist on describing CSS specificity, let me stop you with my own unique powers and clear up his errors before you follow his flawed math and find yourself flung back to earth most painfully.
The confusion has to do with the specificity algorithm being different between CSS specifications. Since most standards-based designers and developers are working with CSS2.1 much of the time, I’m going to show how to calculate specificity according to the CSS2.1 specification. This way, you can make your calculations relevant to the kinds of selectors we’re using in contemporary CSS design.
Here’s an easy way to visualize specificity in CSS2.1:
||# of ID selectors||# of class selectors||# of Element (type) selectors|
The final specificity calculations then would be:
p = 0, 0, 0, 1
p.warning = 0, 0, 1, 1
#content p.warning = 0, 1, 1, 1
Other items of specific interest:
- The universal selector has a specificity of
0, 0, 0, 0
- Inherited values have null specificity
- According to the CSS2.1 specification, it can be interpreted that a pseudo element is calculated as an element, a pseudo-class is calculated as a class, and an attribute selector is also calculated as a class. Note that CSS2 says that pseudo elements should be ignored, further confusing the issue
- As you can see from this chart, if a rule is applied to an element with an inline style, the inline style has higher specificity than anything. So, you’d add a 1 to the beginning of the style in question, let’s say there’s an inline style on some instance of
p, that particular selector would then have a specificity of
1, 0, 0, 1, being the most specific rule of the bunch
And, while it seems natural to drop the comma delimiters and count all this as if it were base 10 (which on first glance make sense) the specification clearly states that a “broad” base is necessary – potentially infinite. While it would be rare to have more than 10 individual selectors in a given category, base 10 doesn’t apply when there are more than 10 selectors present. Eric Meyer explains this a whole lot better than I can in his article Link Specificity.