Tuesday, September 2, 2008

Selector Specificity

When two or more CSS rules target the same (X)HTML document element, the style that is applied to the element is determined by a system called selector specificity. Selector specificity is just a system to calculate how specific a particular CSS selector is. Among two or more CSS selectors, the most specific selector is the one that is applied to the element.

Calculating Specificity

Inline styles have the highest specificity. Second highest in specificity are ID selectors, third are Class selectors, Pseudo-Class selectors and Attribute selectors and last are Element Type selectors and Pseudo-Element selectors.
A selector chain with more than one selector of a specific kind is more specific than a selector chain that has only one or fewer selectors of that kind. An example will make this clear. Assume that the following two CSS selector chains target the same (X)HTML element:
img { float: right; }
div p img { float: left; }

The second CSS rule is more specific because it has more Element Type selectors. Therefore, the second CSS rule will be applied to the element.
When determining the specificity of CSS selectors, it is convenient to represent the specificity as four comma separated numbers - 0,0,0,0 . Each number represents one kind of selector - starting from the left and with the highest specificity - inline styles, and next, ID selectors, and next, Class, Pseudo-Class Selectors and Attribute selectors, and last, with the lowest specificity, Element Type selectors and Pseudo-Element selectors. Each instance of a particular kind of selector is calculated as one point.
Example:
#menu ul li a:link
The selector has one ID selector - #menu, therefore 1 should be added to the third digit (from the right) - 0,1,0,0 . The selector has one Pseudo-Class selector - :link, therefore 1 should be added to the second digit (from the right) - 0,1,1,0 . The selector has three Element Type selectors - ul li a , therefore 3 should be added to the first digit (from the right) - 0,1,1,3 . The element does not have any inline styles therefore the last digit is zero.
The universal selector (*) has a specificity of zero, but this does not mean it has no specificity. Combinators - the space character, the greater-than symbol, the tilde and the plus sign - have no effect on specificity.

No comments: