Tip: Calculate the Specificity of CSS Selectors

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.