Selector Specificity

From CSS Discuss

Jump to: navigation, search

This is intended to be a discussion on how specificity works, how it fits into the cascade, and how to make (practical) sense out of it, from the author's point of view.

How to calculate specificity

The below is taken from http://www.w3.org/TR/REC-CSS2/cascade.html#specificity :

A selector's specificity is calculated as follows:

  • count the number of ID attributes in the selector (= a)
  • count the number of other attributes and pseudo-classes in the selector (= b)
  • count the number of element names in the selector (= c)
  • ignore pseudo-elements.

Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.

Example(s):

Some examples:

* {} /* a=0 b=0 c=0 -> specificity = 0 */
LI {} /* a=0 b=0 c=1 -> specificity = 1 */
UL LI {} /* a=0 b=0 c=2 -> specificity = 2 */
UL OL+LI {} /* a=0 b=0 c=3 -> specificity = 3 */
H1 + *[REL=up] {} /* a=0 b=1 c=1 -> specificity = 11 */
UL OL LI.red {} /* a=0 b=1 c=3 -> specificity = 13 */
LI.red.level {} /* a=0 b=2 c=1 -> specificity = 21 */
#x34y {} /* a=1 b=0 c=0 -> specificity = 100 */

If two rules apply to an element, the first defined in a style sheet and the second that element's style attribute, the latter wins if there are any conflicts. (The latter is given a bonus of +1 to its 'a' value when calculating specificity.)


Personal tools