CSS Selectors, the Cascade and Specificity
Write CSS rules with element, class and id selectors, understand why one rule wins over another, compute specificity by hand, and confirm the winner with real computed styles.
In this lesson you will
- Write selectors for elements, classes and ids
- Predict which rule wins
- Compute specificity as three numbers
- Use inheritance sensibly
About 28 minutes
Why is my text the wrong colour?
Ravi added a rule to make all paragraphs dark grey, and one paragraph stayed green. CSS is called Cascading Style Sheets because several rules can apply to the same element, and the browser needs a procedure to decide which one wins. The procedure has three steps. First, importance: a declaration marked !important beats normal ones. Second, specificity: a more specific selector beats a less specific one. Third, order: when specificity is equal, the rule that appears later wins. Some properties, such as color and font-family, are also inherited: a child element uses its parent’s value unless a rule says otherwise.
Specificity is a score with three numbers, written (a, b, c). Count one in a for each id selector, one in b for each class, attribute or pseudo-class selector, and one in c for each element selector. Compare the numbers from left to right: (1, 0, 0) beats (0, 5, 0), because one id outweighs any number of classes. An inline style attribute beats all selectors, and the universal selector adds nothing. Because specificity wars are painful, good CSS keeps selectors flat, mostly single classes, so that order decides.
| Selector | Specificity (a, b, c) |
|---|---|
| p | (0, 0, 1) |
| .note | (0, 1, 0) |
| p.note | (0, 1, 1) |
| #intro | (1, 0, 0) |
| nav ul li a:hover | (0, 1, 4) |
| #menu .item.active | (1, 2, 0) |
const { JSDOM } = require('jsdom');
const dom = new JSDOM(`<!doctype html><html><head><style>
p { color: black; }
.note { color: green; }
p.note { color: purple; }
#intro { color: blue; }
.late { color: teal; }
.late { color: navy; }
</style></head><body>
<p id="intro" class="note">intro</p>
<p class="note">note</p>
<p>plain</p>
<p class="late">late</p>
<div style="color: crimson"><p>inside inline parent</p></div>
<p class="note" style="color: brown">inline</p>
</body></html>`);
const w = dom.window, d = w.document;
const rows = [...d.querySelectorAll('p')].map(p => [p.textContent, w.getComputedStyle(p).color]);
rows.forEach(r => console.log(r[0].padEnd(22), r[1]));
console.log('DATA ' + JSON.stringify(rows));
intro rgb(0, 0, 255)
note rgb(128, 0, 128)
plain rgb(0, 0, 0)
late rgb(0, 0, 128)
inside inline parent rgb(0, 0, 0)
inline rgb(165, 42, 42)
The browser applied the cascade exactly as predicted. The first paragraph has the id intro and the class note, so four rules match it, and the id selector (1, 0, 0) beats p.note (0, 1, 1), .note (0, 1, 0) and p (0, 0, 1): its colour is blue. The second paragraph has no id, so p.note wins over .note and p, and it is purple. The plain paragraph is matched only by p, so it is black. The “late” paragraph is matched by two rules with the same specificity, so the later one wins: navy.
The last two lines show inheritance and inline style. The paragraph inside the div with color crimson stayed black, not crimson. Inheritance is the weakest source of a value: it applies only when no rule matches the element directly, and the rule p { color: black } matches every paragraph, so it beats the colour inherited from the parent. The last paragraph has an inline style attribute, which outranks every selector, so it is brown. If Ravi wants paragraphs to follow their parents, he should delete the direct rule and set the colour once on a parent, such as body.
Independent check: a small calculator written in Python parsed each selector with regular expressions, counting ids, then classes, attributes and pseudo-classes, then element names, and agreed with the table of six selectors above, including that nav ul li a:hover scores (0, 1, 4) and that #menu .item.active scores (1, 2, 0). The computed colours came from the style engine inside jsdom, and the order of winners matches what the three-step procedure predicts.
Check by hand: for the first paragraph the candidates are (0, 0, 1) from p, (0, 1, 0) from .note, (0, 1, 1) from p.note and (1, 0, 0) from #intro. Comparing from the left, only #intro has a 1 in the first position, so it wins, whatever the others contain. The two .late rules are both (0, 1, 0), so the order decides.
!important and deep selectors such as #page .content ul li a make later changes hard, because you must beat them with something stronger. Prefer one class per component and keep specificity low.
In the developer tools, the Styles panel lists every rule that matches the selected element, in order of priority, with the losing declarations struck through. It is the fastest way to answer “why is it this colour?”.
Every program in this lesson was run while the course was written, with Node.js 22, jsdom 31 (a pure-JavaScript DOM used for tests, not a real browser) and Python 3.13. Browsers, tools and their menus change often, so check the official documentation (MDN, the Node.js docs, your provider) for current behaviour. jsdom implements the cascade for common properties, but not layout, so use a real browser to check how a page looks.
Practice
Write five rules for a bakery menu list and predict the colour of each item before checking. Compute the specificity of the selectors ul.menu li:first-child a and #menu li.sold-out by hand. Explain why a rule in a later stylesheet does not always win.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What decides between two rules of equal specificity?
- The earlier one wins
- The longer one wins
- Random choice
- The later one wins
Order is the last step of the cascade.
What is the specificity of #nav .item a?
- (0, 3, 0)
- (1, 0, 1)
- (1, 1, 1)
- (0, 1, 2)
One id, one class, one element.
Which beats which?
- Ten classes beat one id
- Elements beat classes
- One id beats any number of classes
- Order always wins
Compare the numbers from the left.
Which property values are inherited by default?
- Margins
- Text properties such as color and font-family
- Borders
- Width
Box properties are not inherited.
Does inheritance beat a direct rule?
- Yes always
- No, a direct rule wins
- Only for colours
- Only with !important
Inheritance is the weakest source.
Summary
- Three steps decide a conflict: importance, specificity, order.
- Specificity is (ids, classes, elements), compared from the left.
- Inheritance is weaker than any direct rule.
- Keep selectors flat and low in specificity.
Questions
What does the C in CSS mean?
Cascading: the procedure that picks one value when several rules apply to the same property of one element.
Should I use ids for styling?
It is better to use classes. An id has high specificity, which makes it difficult to override, and an id must be unique on the page.
How do I find out which rule wins?
Inspect the element in the browser's developer tools. The Styles panel shows the matching rules and strikes out the ones that lost.
