Mar 12 2012
CSS Specificity
CSS Specificity comes into play if you have two or more conflicting CSS rules around the same element. There are some basic rules and formula that a typical browser will follow to determine which one is most specific.
If the selectors are the same then the latest one will always take precedence. For example:
a { color: black; }
a { color: white; }
Typically this only happens by accident, and developers usually don’t knowingly add two of the same selectors. Conflicts legitimately come up when you have nested selectors however. Example:
p a { color: black; }
a { color: white; }
In this case you might think that a elements within a p element would be black, but they would actually be colored white due to the specificity of the first selector. In short the more specific a selector, the more preference it will be given when it comes to conflicting styles.
The specificity of a group of nested selectors takes some calculating. You would give every id selector (“#example”) a value of 100, every class selector (“.example”) a value of 10 and every HTML selector (“example”) a value of 1. Adding them up now gives you the specificity value of that style.
- a has a specificity of 1 (1 HTML selector)
- p a has a specificity of 2 (2 HTML selectors – 1+1)
- .example has a specificity of 10 (1 class selector)
- p a.example has a specificity of 12 (2 HTML selectors and 1 class selector – 1+1+10)
- #example has a specificity of 100 (1 id selector)
- body #content .example p has a specificity of 112 (1 HTML selector, 1 id selector, 1 class selector and 1 HTML selector – 1+100+10+1)