Sooner or later two rules will aim at the same element and disagree.
<style>
p { color: green; }
.note { color: blue; }
#intro { color: red; }
</style>
<p id="intro" class="note">What color am I?</p>
The text is red, although the p rule is first and .note is in the middle. The browser compares how specific each selector is, and the most specific one wins. That is specificity.
The ranking
From weakest to strongest:
| Level | Example | Weight |
|---|---|---|
| Universal and combinators | * | 0 |
| Element or pseudo-element | p, ::before | lowest (0,0,1) |
| Class, attribute, pseudo-class | .note, [type="text"], :hover | middle (0,1,0) |
| ID | #intro | high (1,0,0) |
Inline style attribute | style="color: red" | higher still |
Counting it
Write specificity as three numbers: (IDs, classes, elements).
| Selector | Specificity |
|---|---|
p | (0, 0, 1) |
p.note | (0, 1, 1) |
.note | (0, 1, 0) |
nav ul li a | (0, 0, 4) |
#menu a:hover | (1, 1, 1) |
#intro | (1, 0, 0) |
You compare from left to right. One ID beats any number of classes. One class beats any number of elements. So .note (0,1,0) beats nav ul li a (0,0,4), even though the second selector is longer.
Equal specificity: the later rule wins
If two selectors tie, the one written later in the stylesheet wins. This is why link states have an order.
<style>
.box { background: #d0e8f2; padding: 12px; }
.box { background: #fdebd9; }
</style>
<div class="box">The second rule wins: it comes later.</div>
Using the developer tools
When a style does not apply, the Styles panel shows crossed-out rules. Find the rule that won: it is the one that is not struck through. Compare the specificity of the two. See Developer Tools.
Do not count by hand every time
Next: how !important breaks the order, and the full list of what the browser checks in The Cascade.