Sub topic 2
Managing the cascade, specificity and source order
This chapter assumes you can read CSS selectors, know the box model, and have seen a rule lose to another rule without knowing why. It explains how the browser picks a winning declaration. It then shows how to write CSS so that you can predict the winner without opening DevTools.
How the browser picks a winner
Several rules often set the same property on one element. The cascade is the algorithm that chooses one value. It compares competing declarations in a fixed order and stops at the first step that separates them.
For the CSS you write yourself, the steps that matter are:
- Importance. A declaration marked
!importantbeats one that is not. - Cascade layer. Layer order decides, and unlayered styles beat layered styles. A later chapter covers
@layer. - Specificity. The more specific selector wins.
- Source order. If everything else is tied, the declaration that appears last wins.
Inline style attributes sit above ordinary selectors in this process. Browser defaults and user settings are separate origins, and they lose to your styles unless !important is involved.
Large codebases get into trouble at steps 3 and 4. Specificity and source order are implicit, so nothing in the code states which rule is meant to win. The rest of this chapter makes that choice explicit and keeps it small.
Specificity as a three-part score
Specificity is a score with three columns, compared left to right. The score 1,0,0 beats 0,99,0, because a higher value in an earlier column always wins.
| Column | Counts | Examples |
|---|---|---|
| A | ID selectors | `#nav` |
| B | Classes, attributes, pseudo-classes | `.card`, `[type="text"]`, `:hover` |
| C | Type selectors, pseudo-elements | `a`, `h2`, `::before` |
The universal selector * and combinators (>, +, a space) add nothing. Some examples:
| Selector | Score |
|---|---|
| `a` | 0,0,1 |
| `.card` | 0,1,0 |
| `.card a:hover` | 0,2,1 |
| `ul.nav li.active a` | 0,2,3 |
| `#sidebar .card` | 1,1,0 |
Three functional pseudo-classes behave differently from the rest:
:is()and:not()take the specificity of their most specific argument.:is(#a, .b)scores1,0,0even when it matches the.belement.:where()always scores zero, whatever it contains.:has()also takes the specificity of its most specific argument.
The :where() rule is useful for base styles that you want to be easy to override:
:where(.prose) a {
color: var(--color-accent, #0b5fff);
text-decoration: underline;
}This selector scores 0,0,1. A plain .link rule elsewhere overrides it regardless of file order.
Source order as the tie-breaker
When specificity ties, the last declaration wins. This is deliberate. It lets you override a component by writing a rule of equal specificity after it:
.button {
background: #eee;
padding: 0.5rem 1rem;
}
.button-danger {
background: #c00;
color: white;
}Both selectors score 0,1,0. An element with class="button button-danger" gets the red background because .button-danger comes later. The result does not depend on the order of the class names in the class attribute. It depends only on the order of the rules in the stylesheet.
This dependence is what makes source order fragile. If a bundler or an @import reorders the files, the red button silently turns grey. Two rules that must be in a certain order should live next to each other in the same file, or be placed in files whose order is controlled explicitly. The next chapters cover file organisation and layers.
How specificity escalates
Specificity problems usually begin with one reasonable rule and grow through overrides. Suppose a legacy page has this rule:
#sidebar .card a {
color: gray;
}It scores 1,1,1. You now want a featured card link to be gold, so you write the obvious rule:
.card--featured a {
color: gold;
}This scores 0,1,1 and loses, however late it appears in the file. The usual responses make things worse:
- Repeat the ID:
#sidebar .card--featured a. This works, but the next override must be1,2,1or higher. - Add
!important. This works until someone needs to override the override, and then they add a second!importantwith higher specificity. - Chain a class:
.card.card--featured.card--featured a. This inflates the score without adding meaning.
Each workaround raises the minimum score every later rule must reach. This is specificity escalation. After a few years nobody can say which rules are safe to change.
The fix is to lower the baseline, not raise the new rule. Remove the ID from the original, and give the link its own class:
.card__link {
color: gray;
}
.card--featured .card__link {
color: gold;
}The first rule scores 0,1,0 and the second 0,2,0. The modifier context wins because it is more specific, and the reason is visible in the selector.
Keeping specificity flat
A flat specificity profile means that most rules in the codebase score 0,1,0. Then source order alone decides ties, and the order can be reasoned about. The BEM example below shows the pattern, which the next chapters develop:
.card {
padding: 1rem;
border: 1px solid #ddd;
}
.card__title {
font-size: 1.25rem;
}
.card--featured {
border-color: gold;
}<article class="card card--featured">
<h2 class="card__title">Release notes</h2>
<p class="card__body">What changed this week.</p>
</article>Every selector is one class. .card--featured overrides the border colour of .card because it appears later, and a reader can see that by looking at the file.
These habits keep a codebase flat:
- Do not use IDs in selectors. Use them for fragment links and labels, not for styling.
- Do not qualify classes with element types, as in
ul.navordiv.card. This adds a column C point for no benefit and ties the style to the markup. - Keep selectors to one or two compound selectors. A selector like
.page .content .list .item abreaks as soon as the markup changes. - Avoid
!importantin your own components. Reserve it for rules that must never lose, such as a.visually-hiddenhelper. - Avoid inline styles for anything other than values that are computed at runtime. An inline style beats every selector, so it can only be overridden by
!important.
Enforcing low specificity
Habits fade, so teams add a check. A Stylelint configuration can fail the build when a selector grows too specific. Later chapters cover Stylelint in full. This one shows the three rules that matter here:
{
"extends": "stylelint-config-standard",
"rules": {
"selector-max-id": 0,
"selector-max-specificity": "0,2,0",
"declaration-no-important": true
}
}With this configuration, #sidebar .card a and color: gold !important are both errors. A selector such as .card--featured .card__link (0,2,0) passes.
Debugging a rule that loses
When a declaration has no effect, work through the cascade in order:
- Open DevTools and select the element. In the Styles pane, a struck-through declaration lost somewhere in the cascade.
- Check whether another rule sets the same property. The Computed pane lists the winning value and links to its rule.
- Compare the specificity of the two selectors using the table above.
- If the scores tie, compare source order. Look at the file and
<link>order. - Check for
!importantor an inlinestyleattribute on either side.
A fast check is to read the selector aloud as a score. If you can't compute it in your head, the selector is probably too complex.
Exercise
A page has #promo .btn { background: gray; } and later in the same file .btn.btn--primary { background: blue; }. The primary button stays gray. Compute both scores, explain why, and give a fix that does not use !important or an ID.
Show answer
The first selector scores 1,1,0 and the second scores 0,2,0. The ID column is compared first, so the gray rule wins even though the blue rule comes later. Fix it by removing the ID from the first rule, for example .btn { background: gray; } (0,1,0), and keeping .btn--primary { background: blue; } after it. Both are now 0,1,0, so source order decides and the later blue rule wins.
Exercise
Which of these scores higher, :where(.card) a:hover or .card a? Give both scores.
Show answer
.card a scores 0,1,1. :where(.card) a:hover scores 0,1,1 as well: :where() adds nothing, a adds one to column C, and :hover adds one to column B. The scores tie, so the rule that appears later in the stylesheet wins.