CSS specificity: which rule wins
20 Which rule wins
hardFour rules all target the same paragraph. Score their specificity, say which one wins, and do it without reaching for !important.
Stuck? Three hints, smallest first
- 1. Specificity is three numbers: ids, then classes and attributes and pseudo-classes, then element types.
- 2. Compare left to right. One id beats any number of classes; one class beats any number of types.
- 3. On a tie, the rule written later wins. That is the cascade, not specificity.
<div id="intro">
<p class="lede">Which colour am I?</p>
<p>And which colour am I?</p>
</div>
p { color: #5c5c66; } /* 0,0,1 */
.lede { color: #17734b; } /* 0,1,0 */
p.lede { color: #a3341f; } /* 0,1,1 */
#intro p { color: #3055d8; } /* 1,0,1 — this one wins for both paragraphs */
p {
margin: 0 0 8px;
font-size: 0.95rem;
}
8 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
// Score a simple selector the way the cascade does: ids, then classes, then types.
const spec = (sel) => {
const ids = (sel.match(/#[\w-]+/g) || []).length;
const classes = (sel.match(/\.[\w-]+/g) || []).length;
const types = (sel.replace(/[#.][\w-]+/g, ' ').match(/[a-z]+/g) || []).length;
return [ids, classes, types];
};
// Highest score wins; ties go to whichever was written last.
const winner = ['p', '.lede', 'p.lede', '#intro p']
.map((sel) => ({ sel, s: spec(sel) }))
.reduce((best, r) => (r.s.join('') >= best.s.join('') ? r : best));
test('a type selector scores 0,0,1', spec('p'), [0, 0, 1]);
test('a class scores 0,1,0 and outranks it', spec('.lede'), [0, 1, 0]);
test('class plus type scores 0,1,1', spec('p.lede'), [0, 1, 1]);
test('an id plus a type scores 1,0,1', spec('#intro p'), [1, 0, 1]);
test('so the id rule wins for both paragraphs', winner.sel, '#intro p');
test('and it is the blue one', /#intro p\s*\{\s*color:\s*#3055d8/.test(css), true);
test('no !important was needed anywhere', /!important/.test(css), false);
test('all four rules are present, so the cascade has something to resolve', (css.match(/color:/g) || []).length, 4);
Output
Specificity is compared column by column, not added up: 1,0,1 beats 0,1,1 because the first column decides it, which is why an id you added for JavaScript can quietly outrank every class in your stylesheet. Note the #intro p rule wins for both paragraphs, including the one with .lede — the class never gets a look in. !important would settle it too, and it is a debt: the only way to beat it later is another !important, and then you are ranking those against each other instead.