Sub topic 4
Specificity: counting ids, classes and elements
Specificity is the criterion the cascade uses when two competing declarations have the same origin, importance and layer. This chapter assumes you can write CSS rules with selectors, know the difference between an id and a class in HTML, and can inspect an element in browser developer tools. It covers how to calculate a specificity score, how to compare two scores, which selector parts count, and the mistakes that cause most "my style isn't applying" problems.
Where specificity sits in the cascade
When several declarations target the same property on the same element, the browser compares them in a fixed order:
- Origin and importance (including
!important). - Cascade layers.
- Specificity.
- Order of appearance.
Specificity only matters when everything earlier in the list is tied. A declaration inside a later layer beats a more specific selector in an earlier layer, and an !important declaration beats a normal one however it scores. Source order is the final tie-breaker, and it is covered in the next chapter.
Specificity is calculated per selector, not per rule. If a rule has a selector list such as h1, .title, #main, each selector is scored separately against the element it matches.
The three-part score
Specificity is written as three numbers, (a, b, c):
| Column | Counts | Examples |
|---|---|---|
| a | Id selectors | `#intro` |
| b | Class selectors, attribute selectors, pseudo-classes | `.note`, `[type="text"]`, `:hover` |
| c | Type selectors, pseudo-elements | `p`, `a`, `::before` |
The universal selector * and combinators ( , >, +, ~) add nothing. Add up the matches in each column to get the score.
p { color: black; }
.note { color: blue; }
#intro { color: green; }
/* <p id="intro" class="note">Hello</p> renders green:
id (1,0,0) beats class (0,1,0) beats element (0,0,1). */All three rules match the same paragraph. The id rule scores (1,0,0), so it wins whatever the order of the rules.
Comparing scores
Compare the columns from left to right. The first column that differs decides the winner, and the later columns are ignored.
(1,0,0)beats(0,50,50). A single id outweighs any number of classes and elements.(0,2,0)beats(0,1,9). Two classes outweigh one class and nine element types.(0,1,1)and(0,1,1)tie, and the cascade falls through to source order.
A common misreading is to treat the score as one number, such as 0,1,0 → "10". That suggests eleven classes would equal one id. Browsers do not work that way: the columns never carry into each other.
Worked scoring examples
Work through each selector by sorting its parts into the three columns.
| Selector | Score | Reasoning |
|---|---|---|
| `*` | (0,0,0) | The universal selector adds nothing. |
| `li` | (0,0,1) | One type selector. |
| `ul li` | (0,0,2) | Two types. The descendant combinator adds nothing. |
| `.card > .title + p` | (0,2,1) | Two classes and one type. |
| `a[href^="https"]` | (0,1,1) | An attribute selector counts like a class. |
| `a:hover` | (0,1,1) | A pseudo-class counts like a class. |
| `p::first-line` | (0,0,2) | A pseudo-element counts like a type. |
| `#nav .item.active` | (1,2,0) | One id and two classes. |
| `ul#nav li.active a:hover` | (1,2,3) | One id, two classes (`.active`, `:hover`), three types. |
| `#a #b` | (2,0,0) | Each id counts. |
| `[id="intro"]` | (0,1,0) | This is an attribute selector, not an id selector. |
The last row is a useful trick and a trap. [id="intro"] matches the same element as #intro, but it has the specificity of a class. Use it deliberately if you want to select by id without the id's weight.
Inline styles
A declaration in an element's style attribute beats any selector in the same origin and importance, because inline declarations are treated as more specific than anything a stylesheet selector can reach.
<p id="intro" style="color: purple;">Hello</p>#intro { color: green; }The paragraph is purple. Inline styles are hard to override from a stylesheet, so most teams avoid them for anything that needs to stay adjustable. The usual escape hatch is !important in the stylesheet, which wins over a normal inline declaration. Use it sparingly.
Which selector parts count
Pseudo-classes and the functional ones
Simple pseudo-classes such as :hover, :focus, :first-child and :checked each add one to the class column. :nth-child(2n+1) also adds one.
A few functional pseudo-classes score by their arguments instead:
:not(X)has the specificity of its most specific argument.:not(#a, .b)scores(1,0,0). The:not()itself adds nothing.:is(X, Y)also takes the most specific argument in its list.:has(X)follows the same rule as:is().:where(X)always contributes zero.
The next chapter covers :is(), :where() and :not() in more detail. For now, the useful consequence is that the argument is what counts, not the function name. :not(.hidden) scores (0,1,0).
Pseudo-elements
::before, ::after, ::first-line and ::placeholder count in the element column. In p::first-line, p and the pseudo-element give (0,0,2).
Nesting
In native CSS nesting, the & selector takes the specificity of the parent selector list, as if it were wrapped in :is(). If the parent is .card, #hero, then & scores as the largest, (1,0,0).
.card {
color: black;
& .title { color: navy; } /* scores (0,2,0): .card plus .title */
}Nesting can raise specificity without looking like it. Deeply nested rules inherit the weight of every level above them.
A full example
Here is a slightly realistic case where the wrong rule seems to win.
<nav id="main-nav">
<ul>
<li class="item active"><a href="/home">Home</a></li>
<li class="item"><a href="/about">About</a></li>
</ul>
</nav>#main-nav a { color: gray; }
.item.active a { color: crimson; }
a:hover { color: orange; }The scores are:
#main-nav ais(1,0,1)..item.active ais(0,2,1).a:hoveris(0,1,1).
Every link matches #main-nav a, and (1,0,1) is the highest of the three. The "Home" link is therefore gray, not crimson, and hovering does not turn it orange. The id in the first selector outweighs both later rules.
There are two reasonable fixes. You can raise the other rules to match, for example #main-nav .item.active a at (1,2,1). Or you can lower the first rule by removing the id, for example .nav a. Lowering is usually better, because it avoids a race where every new rule needs a heavier selector than the last.
Inheritance has no specificity
Inherited values are not declarations on the element, so they do not take part in specificity at all. Any rule that targets the element directly beats an inherited value, even one from a very specific parent rule.
#page .content { color: green; }
* { color: red; }<div id="page" class="content">
<p>Text</p>
</div>The <p> is red. The * rule targets the paragraph directly with score (0,0,0), and the green value is only available through inheritance, which the cascade treats as a last resort. This is why a blanket rule like * { color: red; } can break inheritance across a whole page. Inheritance is covered in a later chapter.
Common errors and how to avoid them
- Reading the score as a decimal number. Compare column by column, never as one number.
- Forgetting that attribute selectors and pseudo-classes weigh the same as classes.
a[href]anda.linktie. - Assuming order beats specificity. Order only breaks ties. A rule at the top of the file with an id wins over a later rule with a class.
- Escalating selectors. Writing
body #main .content ul li ato beat another rule makes the next override harder. Prefer a flat, low-specificity style, and put overrides in a later layer if you need control. - Repeating a class to raise the score.
.btn.btn.btnscores(0,3,0)and works, but it is a hack that hides intent. Layers or a well-chosen selector say the same thing more clearly. - Using
!importantto fix a specificity problem. It moves the conflict to a different tier of the cascade, where later fixes need!importanttoo.
Keeping specificity low
Teams that avoid specificity problems tend to follow the same few habits.
- Style with single classes and avoid ids and long descendant chains.
- Keep selectors flat, so most rules score
(0,1,0). - Use
:where()to wrap selectors for default styles that should be easy to override, since it adds zero. - Put third-party or base CSS in an earlier cascade layer so that your rules win without raising specificity.
- Use source order deliberately: group base rules before variants.
Because specificity is the third criterion, none of these tools change the rules. They only keep the numbers small enough that the last two criteria, layers and order, can do the work.
Exercises
Exercise
Calculate the specificity of nav ul li.active > a:hover::after, and say whether it beats #menu a for an ::after pseudo-element on a link that matches both.
Show answer
The first selector has no ids. Its classes and pseudo-classes are .active and :hover, which gives 2. Its types and pseudo-elements are nav, ul, li, a and ::after, which gives 5. The score is (0,2,5). The selector #menu a scores (1,0,1) and has one id. Compare left to right: the id column is 1 against 0, so #menu a wins the specificity comparison. (In practice the two selectors only compete if the second one also targets the pseudo-element, but the scores are as calculated.)
Exercise
Two rules target the same <button class="btn primary">. Rule 1 is button.btn { background: gray; } and rule 2 is .primary { background: blue; }. Rule 2 comes later in the file. Which color does the button get, and what change makes .primary win without using !important or an id?
Show answer
Rule 1 scores (0,1,1) and rule 2 scores (0,1,0). Rule 1 has the higher specificity, so the button is gray even though rule 2 comes later. To make rule 2 win without !important or an id, you can lower rule 1 to .btn at (0,1,0) so the scores tie and the later rule wins, or raise rule 2 to button.primary at (0,1,1) so it ties with rule 1 and wins by order. Lowering rule 1 is the better fix because it keeps scores small.
Exercise
A page sets #sidebar { color: green; } and * { color: red; }. A <p> inside the sidebar has no other rules. What color is the paragraph, and why?
Show answer
The paragraph is red. The #sidebar rule only reaches the paragraph by inheritance. The * rule matches the paragraph directly, with a score of (0,0,0). A directly matched declaration always beats an inherited value, because inherited values do not take part in specificity.