Unlike the examples of style collision earlier in this chapter, where closeness
could be used to declare a winner, here you’ve got both styles located at the
same degreeof closeness (the same specificity). Both of these style definitions
are located in external style sheets.
In this case, the browser does a little bizarre math to make the decision
about which style to use. As before, the more “specific” style wins. But what
counts as specificity in this contest? It’s not the same as the “closeness”
factor. The browser has to do a bit of strange calculation, but you really can’t
call this math. It’s just an odd kind of accumulation of values where some
styles have orders of magnitude more weight than others. Don’t bother your
pretty head about this stuff if you don’t find peculiar calculations interesting.
What does the browser do to calculate the specificity of two competing styles
if their “closeness” factor is identical? Three things:
Looks at a style and counts the number of ID attributes it has, if any
Counts the number of class attributes, if any
Counts the number of selectors (you can group selectors in a style like
this: h1, h2, h3)
The browser doesn’t then add these numbers together; it merely concatenates
the digits. Perhaps this is some kind of arithmetic used by aliens in their
galaxy, but I’ve sure never heard of it. Imagine if you got the number 130 by
the following concatenation process:
1 apple, 3 oranges, 0 bananas = 130
This process gives apples ten times the “weight” of oranges, and 100 times
the weight of bananas. Here are a couple of examples showing how it works
when used to determine specificity in a CSS. Just pretend you’re back in
third-grade math class.
Attention, class! What is the specificity number for this selector?
ul h1 li.red {color: yellow;}
Anyone get the answer 13?
The correct answer is 13. You have
0 IDs, 1 class attribute (red), and 3 selectors (ul h1 li)
That “adds up,” so to speak, to 013. Now, kiddies, who can explain how you
get a specificity of 1 for the following selector definition?
H1 {color: blue;}
44 Part I: The ABCs of CSS