CSS Specificity is one of the most difficult concepts to grasp when working with stylesheets. In a nutshell, specificity determines which CSS rule is selected by the browser when multiple rules match a given HTML element. It’s important to understand it in order to know:
- why some rules are rejected when debugging a page
- how to overwrite a given rule with the minimal syntax
You can calculate specificity, or you can use a simpler and more intuitive analogy. Let’s review the former.
The W3C proposes the following method for calculating a selector’s specificity:
- a = the number of #id
- b = the number of .class + [attribute] + :pseudo-class
- c = the number of TYPE + :pseudo-element()
- ignore the universal selector
- concatenate the three numbers a-b-c to obtain the specificity (assume a large base)
Examples (simplified from W3C):
1 2 3 4 5 6 7 8 9
You can test your understanding of this method with a Specificity Calculator.
Because these calculation are tedious to employ on a daily basis, various analogies have been proposed to illustrate how specificity works:
However, I still find these systems either complex or hard to remember, so I came up with yet another analogy, based on the Olympic medal table.
The CSS Olympic Medal Table
The ICO uses the gold first system, a ranking order based first on the number of gold medals won, then silver and bronze. The 2010 Winter Olympics medal table illustrates how this works:
CSS Specificity works the same way: it’s not the number of selector that counts, it’s how many of the right ones you have.
Here is how the CSS Olympic Medal Table works:
- use the gold first raking system
- gold = the number of #id
- silver = the number of .class + [attribute] + :pseudo-classe
- bronze = the number of TYPE + :pseudo-element()
Our previous example can be converted as follows:
This technique is faster because you don’t have to count at all of the selectors to find out which rule wins!