Jean-Francois Paradis

Web Developer + Architect

CSS Specificity Using the Olympic Medals Table

| Comments

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.

Using Calculation

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
*                  /* a=0 b=0 c=0 -> specificity =   0 */
H1                 /* a=0 b=0 c=1 -> specificity =   1 */
H1 A               /* a=0 b=0 c=2 -> specificity =   2 */
H1+P A             /* a=0 b=0 c=3 -> specificity =   3 */
FORM *[type=text]  /* a=0 b=1 c=1 -> specificity =  11 */
P A:hover          /* a=0 b=1 c=2 -> specificity =  12 */
P.center A.red     /* a=0 b=2 c=2 -> specificity =  22 */
#main              /* a=1 b=0 c=0 -> specificity = 100 */
#main:not(DIV)     /* a=1 b=0 c=1 -> specificity = 101 */

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:

Rank Country Gold Silver Bronze Total
1 Canada 14 7 5 26
2 Germany 10 13 7 30
3 United States 9 15 13 37
4 Norway 9 8 6 23
5 South Korea 6 6 2 14

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:

Rank Selector Gold Silver Bronze
1 #main:not(DIV) 1 0 1
2 #main 1 0 0
3 P.center A.red 0 2 2
4 P A:hover 0 1 2
5 FORM *[type=text] 0 1 1
6 H1+P A 0 0 3
7 H1 A 0 0 2
8 H1 0 0 1

This technique is faster because you don’t have to count at all of the selectors to find out which rule wins!

Comments