Have you ever added a new rule to your CSS stylesheet, but seen no change in the results on the page in the browser window? Maybe the new selector wasn’t specific enough to overrule and existing rule in your stylesheet. Here’s how to mathematically calculate the specific weight of your CSS selectors.
The W3C uses mathmatical formulas to determine the weight of any particular style. The more weight a style has, the more specific it is.
In strict XHTML (where you do not use inline styles), specificity is figured using three numbers. For example 0, 0, 0.
The first number on the left is the number of IDs in the selector. ID wins the most points in this game. A selector with the most ID points is always the most specific.
#header specificity = 1, 0 , 0
#header #logo specificity = 2, 0, 0
The second number represents the number of class, pseudo-class and attribute selectors.
.post_head specificity = 0, 1, 0
#content .post_head specificity = 1, 1, 0
The third number represents the number of element and pseudo-element selectors.
p specificity = 0, 0, 1
#content p specificity = 1, 0, 1
#header #logo p specificity = 2, 0, 1
If there’s a tie for the number of IDs, tne the selector with the most classes wins. If there’s still a tie, the selector with the most elements wins. If two selectors are still tied, then the conflict is resolved by the position of the rule in the cascade.
If inline styles are allowed (as in transitional XHTML), then four numbers are needed. The weight of an inline style is given in the first position. Here are some examples using four digits.
#content specificity = 0, 1, 0, 0
#content p specificity = 0, 1, 0, 1
If an inline style were added in the HTML, say to a P element in the content div, then the numbers would be
1, 1, 0, 1
In this case the specificity would be greater for the paragraph with the inline style than for other paragraphs in the content div, thus winning the specificity battle.
Brilliant tip thanks!
Good article, although you’ve forget to clarify a point that many people are mistaken about.
The commas in the “number” formed can’t be left out, as there is no base number for these rules. For example, you can’t have 11 classes outrule 1 id.
I’ve written a little bit about it myself, covering the finer points about general selectors (*) and !important declarations:
http://www.onderhond.com/blog/work/css-specificity
NIels, thanks for the addition. I decided keep it basic and omit what happens when a number in any position goes above 9 in this article, but your link is welcome. You also mention !important.