Friday, February 11, 2011

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 an existing rule in your stylesheet. This article will explain mathematically calculate the specific weight of your CSS selectors.


Instructions


1. The W3C uses mathematical formulas to determine the weight of any particular style. The more weight a style has, the more specific it is.


2. In strict XHTML (where you do not use inline styles) specificity is figured using three numbers. For example 0, 0, 0. These positions are referred to as a, b, c. Don't think of them as numbers in the normal sense.


3. The first number on the left (position a) is the most important, or most heavily weighted. 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


4. 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


5. 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


6. If there's a tie for the number of IDs, then 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.


7. A value in the first position will always have more weight than a value in any other position, no matter what values are in other other positions. For example, a value of 1, 0, 0 still has a higher specificity than a value of 0, 0, 10.


8. 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.







Tags: content specificity, inline style, selector with, selector with most, specificity content, with most, first number