CSS Specificity & the Cascade
When two CSS rules target the same element and property, which one wins? The answer
comes from two algorithms: specificity (which selector is more precise) and the
cascade (a broader set of rules including source order, origin, and !important). Understanding both is what separates developers who fight with
CSS from those who write it confidently.
!important — when and why not
@layer
The Specificity Model — (A, B, C)
Specificity is represented as three independent counters. When two rules conflict, the browser compares them column by column, left to right — a higher A always beats any number of B or C:
#id
.class · [attr] · :hoverdiv
· p · ::before* — universalpdiv p.btna:hover.nav > a.active#header#nav .btn:hover(0,100,0) loses to (1,0,0). The columns
do not carry over. Think of them as three separate numbers compared from left to right — not as a
three-digit decimal number.
How to Calculate Specificity
Count each selector type in the full selector expression. Combinators and the
universal selector * contribute nothing. Special cases to know:
- Class selectors:
.btn,.active - Attribute selectors:
[type="text"],[href] - Pseudo-classes:
:hover,:nth-child(),:not()* :is(),:has()— takes specificity of most specific argument:where()— always contributes (0,0,0)
*universal = (0,0,0) — no specificity- Combinators (space, >, +, ~) = nothing
:not(X)= X's specificity, not:not()itself:where(X)= always (0,0,0) regardless of Xinline style=""beats any selector — equivalent to (1,0,0,0)!importantoverrides everything — handled by cascade, not specificity
/* (A, B, C) — count each selector type */
* /* (0,0,0) */
p /* (0,0,1) — 1 element */
p::first-line /* (0,0,2) — element + pseudo-element */
div p /* (0,0,2) — 2 elements, combinator ignored */
.btn /* (0,1,0) — 1 class */
a:hover /* (0,1,1) — 1 pseudo-class + 1 element */
input[type="text"] /* (0,1,1) — attr selector + element */
.nav > a.active /* (0,2,1) — 2 classes + 1 element */
#header /* (1,0,0) — 1 ID */
#nav .btn:hover /* (1,2,0) — ID + 2 class-level */
/* :not() — takes specificity of its argument */
a:not(.active) /* (0,1,1) — .active is (0,1,0) + a is (0,0,1) */
:is(h1, h2, h3) /* (0,0,1) — max specificity of h1/h2/h3 */
:is(#id, .class) /* (1,0,0) — takes #id's high specificity! */
:where(h1, h2, h3) /* (0,0,0) — always zero */
The Cascade — How Browsers Decide
When multiple declarations set the same property on the same element, the browser resolves the conflict using the cascade — a series of steps applied in order. If any step produces a clear winner, it stops there:
!important
declarations reverse this order — user-agent !important
beats author !important.
@layer)@layer lets you define
explicit ordering. Unlayered styles win over any layer. Within layers, later-declared layers win. This
gives you control independent of specificity./* Step 3: Specificity wins */
p { color: red; } /* (0,0,1) — loses */
.intro { color: blue; } /* (0,1,0) — wins */
/* Step 4: Source order wins (equal specificity) */
.btn { color: red; } /* (0,1,0) — earlier, loses */
.btn { color: blue; } /* (0,1,0) — later, wins */
/* The "link state" order LVHA relies on source order */
a:link { color: blue; } /* all same specificity */
a:visited { color: purple; }
a:hover { color: orange; } /* last → wins when hovered */
a:active { color: red; } /* last → wins when active */
Inheritance
Some CSS properties are inherited — when you set them on a parent, all descendants automatically use that value unless they have their own. Others are not inherited — children start from the browser default.
This <p> also blue — inherits from parent.
This <strong> is orange — it has its own color rule, overriding the inherited value.This <em> is purple — also overriding locally.
Back to blue — no local override on this p.
color · font-size · font-family · font-weight · line-height · letter-spacing · text-align · text-indent · visibility · cursor · list-style · word-spacing
background · border · margin · padding · width · height · display · position · float · overflow · box-shadow · transform
/* Explicitly control inheritance */
p { color: inherit; } /* force inherit from parent */
p { color: initial; } /* reset to browser's default value */
p { color: unset; } /* inherits if inherited, else initial */
p { color: revert; } /* reverts to browser/user stylesheet default */
/* Reset ALL properties */
.reset { all: unset; } /* remove ALL author styles */
.reset { all: revert; } /* restore browser defaults */
/* Practical: inherit border-box everywhere */
html { box-sizing: border-box; }
*, *::before, *::after {
box-sizing: inherit; /* inherits border-box from html */
}
/* Practical: base font on body */
body { font-family: Arial, sans-serif; color: #1e293b; }
/* All descendants inherit font and color automatically */
!important — The Override of Last Resort
!important bypasses specificity entirely for
normal declarations. Any !important declaration beats any non-!important declaration, regardless of specificity. When two !important declarations conflict, specificity is used again — but for the
!important declarations only.
.imp-btn-normal { color: red } → loses to
#btn-id.imp-btn-normal { color: purple }
.imp-btn-important { color: green !important }
wins even against #id { color: red }
/* !important overrides specificity */
#main .content p { color: blue; } /* (1,1,1) — loses */
p { color: red !important; } /* (0,0,1) — wins! */
/* Two !important rules — specificity applies between them */
p { color: red !important; } /* (0,0,1) !important — loses to ↓ */
.para { color: blue !important; } /* (0,1,0) !important — wins */
/* ✓ Legitimate uses */
.sr-only { position: absolute !important; } /* screen reader utility */
.hidden { display: none !important; } /* override any display */
.text-red { color: red !important; } /* utility-first (Tailwind) */
/* ✗ Avoid in component styles — leads to !important wars */
.card { background: white !important; } /* DON'T — breaks theming */
Cascade Layers — @layer
@layer is a modern CSS feature (all browsers since
2022) that lets you group styles into explicitly ordered layers. Later layers win regardless of
specificity, and unlayered styles always win over any layer. This solves the classic problem of
specificity wars in large codebases:
/* Step 1: Declare layer order — later = higher priority */
@layer base, theme, components, utilities;
/* Step 2: Add styles to each layer */
@layer base {
*, *::before, *::after { box-sizing: border-box; }
body { font-family: system-ui, sans-serif; }
}
@layer theme {
:root { --color-primary: #264de4; }
}
@layer components {
.btn {
background: var(--color-primary);
padding: .5rem 1rem;
}
}
@layer utilities {
.hidden { display: none; } /* beats any component style */
.sr-only { position: absolute; }
}
/* Unlayered styles always win (e.g., page-specific overrides) */
.hero .btn { font-size: 1.25rem; }
/* Layer and @import */
@import url("reset.css") layer(base);
@import url("theme.css") layer(theme);
Best Practices — Writing Predictable CSS
| Situation | Recommendation | Why |
|---|---|---|
| Styling components | Use class selectors .btn |
(0,1,0) — easily overridable |
| Site-wide base | Element + :where() |
Zero specificity — never blocks overrides |
| Avoid IDs in CSS | Use classes instead | IDs create (1,0,0) that is hard to beat without !important
|
| Need to override third-party | @layer unlayered rules |
Unlayered always beats any layer |
| Utility classes | Put in the highest @layer |
Wins over components without !important |
| Forced override | Increase specificity first | Add a parent class before reaching for !important |
!important |
Only for utilities, a11y | Cannot be overridden — breaks theming and maintenance |
| LVHA link states | Always declare in order | All same specificity — source order decides |
Try It Yourself
Experiment with specificity conflicts, inheritance, !important and @layer — change selectors and watch which rule wins:
Quick Check — Chapter 38
— Column A: 1 vs 0 → ID wins immediately. The browser stops comparing.
— Columns B and C are never even considered.
The columns are not digits in a three-digit number — they are three separate numbers compared from left to right. This is why (0,100,0) loses to (1,0,0): A=0 vs A=1, ID wins regardless of B and C.
This is why avoiding IDs in CSS is a best practice — they create a specificity level that requires either another ID or
!important to override.
1. Origin and Importance: CSS comes from three origins — user-agent (browser default), author (your stylesheets), and user (reader preferences). For normal declarations, author beats user-agent. But
!important reverses this: user-agent !important
beats author !important.2. Cascade Layers (@layer): Within the author origin, explicitly declared layers are compared. Later-declared layers win. Unlayered styles always win over any layer.
3. Specificity: If same origin/layer, compare (A,B,C) specificity. Higher specificity wins.
4. Source Order: If everything else is equal, the last declaration in source order wins. This is why the LVHA order matters for link states — all four pseudo-classes have the same specificity, so the one declared last wins.
:is(#id, .class) has specificity (1,0,0) — ID
level.:is() takes the specificity of its most specific
argument. Even if the selector currently only matches .class, the entire :is() expression
carries the specificity of #id — (1,0,0).This is a common gotcha. If you write
:is(#id, .class, p) a { color: blue }, the selector has specificity
(1,0,1) because of the #id inside :is(). Even if the element you're targeting only matches via the p part, the specificity is still (1,0,1).This is in contrast to
:where(), which always contributes (0,0,0)
regardless of its arguments — making it ideal for base styles that should never win a specificity
battle.
inherit — forces the property to take the computed
value of the same property on its parent element, regardless of whether it would normally be inherited.
Useful for non-inherited properties like border.initial — resets the property to its CSS
specification default value (not the browser stylesheet). For color,
the initial value is black according to the spec (not whatever the
browser default is).unset — acts like inherit for inheritable properties and like initial for non-inherited ones. A convenient "smart reset."revert — rolls the property back to the browser
(user-agent) stylesheet value, not the CSS spec initial value. For example, display: revert on a <div>
restores display: block (browser default), not display: inline (spec initial).
!important wars break out.@layer solves this by making layer order the primary resolution factor — above specificity:
— Define layers:
@layer base, theme, components, utilities;— Styles in
utilities layer always win over components, even with lower specificity— A utility
.hidden { display: none } with (0,1,0) beats a component
#card { display: flex } with (1,0,0)Within each layer, normal specificity still applies. This means you can write low-specificity selectors in utility layers and still have them win over high-specificity selectors in component layers — without
!important.Unlayered styles always win over any layer, providing an easy escape hatch for page-specific overrides.
.nav > ul > li > a:hover?!important. How is the conflict resolved?@layer base, components, a rule in components has specificity (0,1,0) and a rule in base has specificity (1,0,0). Which wins?- Specificity (A,B,C): A = IDs, B = classes/attributes/pseudo-classes, C = elements/pseudo-elements. Columns are independent — (1,0,0) beats (0,100,0). Combinators add nothing.
- :is() specificity = most specific argument. :where() = always (0,0,0). Use :where() for base styles that should never block overrides.
- The 4 cascade steps: 1) Origin + importance, 2) @layer, 3) Specificity, 4) Source order. First step to produce a winner stops the process.
- Inheritance: Typography properties (color, font-*) inherit down the tree. Box model
properties (margin, padding, border, background) do not. Use
inherit,initial,unset,revertto control it explicitly. - !important: Beats all non-!important declarations. When two !important rules conflict, specificity is used between them. Avoid in component styles — legitimate uses: utilities, a11y overrides.
- @layer: Later-declared layers win over earlier layers regardless of specificity. Unlayered styles always beat any layer. Enables predictable CSS architecture without specificity wars.
- Best practices: Use class selectors for components. Avoid IDs. Use :where() for base styles. Put utilities in the highest layer. Prefer increasing specificity over !important.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.