Sub topic 15
Keeping Specificity Low and Manageable
This chapter assumes you can read selectors, calculate a specificity triple, and explain how source order, !important, and @layer fit into the cascade. Here you will use that knowledge to write stylesheets that stay easy to change.
Why specificity grows out of control
Specificity problems build up over time. A developer needs to override a rule and can't. They add an ID, or chain another class, or write !important. The next developer must beat that rule, so they write something stronger. After a year, nobody can change a style without a fight.
Each step is a reasonable local fix, but the cumulative result is a stylesheet where selector strength matters more than intent. The goal of this chapter is to keep strength roughly equal across rules, so that source order and layers make the decisions.
The usual causes are:
- Styling with IDs, which add a whole (1,0,0) that no number of classes can match.
- Long descendant chains copied from the HTML structure, such as
#main .content ul li a. - Qualifying classes with types, such as
div.card, which adds (0,0,1) for no benefit. - Using
!importantto win a fight instead of to set a deliberate policy. - Overrides written with more selectors than the original, in an arms race.
Principle 1: Style with single classes
A single class selector is (0,1,0). If most of your rules are one class, then any rule can be overridden by another one class that appears later. Source order becomes the tiebreaker, and that is easy to reason about.
/* Hard to override: (1,1,1) */
#sidebar ul.menu a { color: navy; }
/* Easy to override: (0,1,0) */
.menu-link { color: navy; }To override the second rule, you write another .menu-link rule, or a modifier class, later in the file. To override the first you must write something with an ID or switch to !important.
Use IDs for fragment links and JavaScript hooks, and keep them out of your CSS selectors. If you inherit a stylesheet with ID selectors, you can match the same element with an attribute selector such as [id="main"]. It counts as (0,1,0), the same as a class, so it avoids the ID weight without changing the markup.
Principle 2: Keep selectors short and flat
Every extra part of a selector adds weight and couples your CSS to the HTML structure. If a designer wraps a list in a new div, a rule like .page > .content > ul > li breaks. A class on the element survives the change.
Compare the two approaches below.
| Brittle selector | Specificity | Flatter alternative | Specificity |
|---|---|---|---|
| `.page .content ul li a` | (0,2,3) | `.nav-link` | (0,1,0) |
| `div.card` | (0,1,1) | `.card` | (0,1,0) |
| `#main p.note` | (1,1,1) | `.note` | (0,1,0) |
Naming conventions such as BEM (Block, Element, Modifier) exist largely to enforce this flatness. In BEM, a card title is .card__title and a highlighted card is .card--featured. Every selector is a single class, so specificity stays at (0,1,0) throughout. You don't have to adopt BEM, but the discipline it imposes is the point.
Principle 3: Use modifiers, not stronger selectors
When a variant needs different styling, add a class to the element instead of writing a more specific selector.
.btn { background: gray; color: white; }
.btn-primary { background: teal; }
.btn-danger { background: crimson; }All three rules are (0,1,0). The modifier classes come after .btn, so they win when both classes are present on an element. The order of rules is the only thing that decides the outcome, and that is easy to see by reading the file.
A common mistake is to write .btn.btn-primary "to be safe". That raises specificity to (0,2,0) and makes any later override need two classes too.
Principle 4: Control specificity with :where() and :is()
You saw earlier that :where() always contributes zero, while :is() takes the specificity of its most specific argument. That makes :where() a tool for writing base styles that are trivially easy to override.
:where(.prose) a { color: blue; } /* (0,0,1) */
.link-muted { color: gray; } /* (0,1,0) */An <a> inside .prose with the class link-muted is gray. Without :where(), the first rule would be (0,1,1) and would beat .link-muted, forcing you to write a stronger override. Library and design-system authors use this pattern so that consumers can customize styles with plain single-class rules.
Be careful with :is(). Writing :is(.a, #b) p gives the whole selector the weight of the ID, even when the element matched through .a. If you only want grouping, prefer :where().
Principle 5: Order your stylesheet from general to specific
Source order only helps if you write it deliberately. A reliable arrangement is:
- Resets and element defaults (type selectors).
- Base components (single classes).
- Variants and modifiers.
- Page-specific and utility rules.
Each tier overrides the one before it through order alone. If a rule in tier 2 must beat one in tier 4, that is a sign that something is arranged wrongly.
Principle 6: Let @layer carry the ordering
Source order can break when you load third-party CSS or split files. Cascade layers make the order explicit and independent of selector weight. You declare the layer order once, and later layers win for normal declarations.
@layer reset, base, components, utilities;
@layer reset {
* { margin: 0; box-sizing: border-box; }
}
@layer base {
a { color: blue; }
}
@layer components {
.card a { color: navy; }
}
@layer utilities {
.text-red { color: red; }
}An element <a class="text-red"> inside .card is red. The utilities layer is last, so it wins even though .card a is (0,1,1) and .text-red is (0,1,0). Specificity only matters within a single layer.
Layers also help with third-party code. Import a framework into an early layer, and all your own unlayered styles beat it, regardless of how strong its selectors are.
@import url("framework.css") layer(vendor);
@layer vendor, theme;Unlayered styles beat every layered style for normal declarations. If you put some of your code in layers and leave other code unlayered, the unlayered code always wins. Decide early whether everything goes in a layer.
Principle 7: Treat !important as a policy tool
Some uses of !important are legitimate. Utility classes like .hidden { display: none !important; } are designed to win unconditionally. A rule for prefers-reduced-motion that must turn off animations everywhere is another case.
The problem is !important used as a fix. Once one rule has it, the only way to override that rule is another !important with higher specificity or a more favorable origin. Reserve it for utilities whose purpose is to always win, and write those utilities in one place so you can see all of them.
Refactoring a heavy selector
Suppose you have this stylesheet, and a new "compact" variant needs a smaller font.
#sidebar .nav ul li a { font-size: 1rem; } /* (1,1,3) */To override it without changing the markup, you would need an ID or !important. The cleaner fix is to put a class on the links and move the rule.
@layer components {
.nav-link { font-size: 1rem; }
.nav-link-compact { font-size: 0.875rem; }
}The markup becomes <a class="nav-link nav-link-compact">. Both rules are (0,1,0), and the modifier comes later, so it wins.
Do this refactoring in small steps. Add the new class names to the HTML, add the new low-specificity rules, check the page, and only then delete the old selector. Changing everything at once makes it hard to find which edit caused a visual regression.
Common mistakes
- Mixing layered and unlayered CSS accidentally. Unlayered rules beat all layers, which can make a new layer look broken.
- Using
:is()where:where()was intended. The heavy argument raises the whole selector. - Fixing a conflict by copying the winner's selector and adding one more part. This repeats the arms race. Ask why the first rule was so strong.
- Declaring layers after they are used. The first mention of a layer name fixes its order, so declare the full order at the top of your stylesheet.
Summary of the habits
- Style with single classes, and keep IDs for non-styling uses.
- Avoid descendant chains and type qualifiers unless the structure is the point.
- Use modifier classes instead of stronger selectors.
- Use
:where()for base styles that others should override. - Declare cascade layers up front and keep third-party CSS in an early layer.
- Keep
!importantfor utilities.
Exercise
A stylesheet has #page .card a { color: navy; } and a later rule .link-accent { color: orange; }. An <a class="link-accent"> inside .card inside #page stays navy. Give two ways to fix it without using !important or adding another ID.
Show answer
The first rule is (1,1,1) and the second is (0,1,0), so navy wins. Fix 1: lower the original by giving the link a class, such as .card-link { color: navy; } at (0,1,0), and place .link-accent after it so source order picks orange. Fix 2: put the original rule in an earlier layer (for example @layer components) and .link-accent in a later layer (for example @layer utilities), declared as @layer components, utilities;. The later layer wins regardless of specificity.
Exercise
You write :is(.prose, #article) a { color: blue; } as a base style, and a colleague's .link-muted { color: gray; } fails to override it. Why, and what change makes the base style easy to override?
Show answer
:is() takes the specificity of its most specific argument, so the selector is (1,0,1) because of #article, even for elements matched through .prose. That beats .link-muted at (0,1,0). Replace :is() with :where(), giving :where(.prose, #article) a, which has specificity (0,0,1), so .link-muted wins.