Untangling the Cascade, Specificity and Layers
Work out which declaration wins a conflict using origin, cascade layers, specificity, source order and inheritance, and resolve the conflict without reaching for !important.
Contentsand lesson path
On this page
- The brief
- Step 1: collect the competing declarations
- Step 2: compare cascade layers
- Step 3: compare specificity, then source order
- Step 4: resolve conflicts without !important
- Check your understanding
- Apply it
- Review prompt
Lessons of CSS Cascade & Box Model
- Selectors and How Rules Find Elements Concept · 20 min
- Untangling the Cascade, Specificity and Layers Worked example · 25 min
- Boxes, Flow, Display and Positioning Concept · 25 min
- Units, Type, Color and Motion Concept · 25 min
- Lab: Debug a Broken Stylesheet in DevTools Lab · 25 min
- Check: Predict the Computed Style Knowledge check · 10 questions
What you will learn
- Predict which declaration wins using origin, cascade layers, specificity, source order and inheritance, and resolve conflicts without !important.
Prerequisites: Semantic HTML
01. The brief
You have joined a small project. Its stylesheet has grown the way stylesheets do: a reset, two cascade layers for base styles and components, and a handful of unlayered rules added by whoever needed them last. Nothing uses !important, yet people keep "fixing" conflicts by adding more specific selectors, and nobody can say why the colours come out as they do.
Your task: predict the computed colour of five elements from the source alone, then verify in the browser. Along the way you will assemble the full decision order the cascade uses — and learn the moves that resolve conflicts cleanly, so that the next person does not inherit another mystery.
@layer reset, base, components;
/* Case A: id vs class vs type */
#hero { color: navy; }
.panel { color: crimson; }
div { color: olivedrab; }
/* Case B: same specificity twice */
.tag { color: sienna; }
.tag { color: seagreen; }
/* Case C and D: layers, then one unlayered rule */
@layer base {
.alert { color: firebrick; }
#special { color: indigo; }
}
@layer components {
.alert { color: goldenrod; }
}
.alert { color: teal; }
/* Case E: :where() contributes zero specificity */
:where(#sidebar) p { color: purple; }
p { color: dimgray; }<div id="hero" class="panel">hero</div>
<span class="tag">tag</span>
<p class="alert">alert</p>
<p id="special" class="alert">special alert</p>
<aside id="sidebar"><p>sidebar note</p></aside>02. Step 1: collect the competing declarations
The cascade arbitrates among declarations that target the same element and set the same property. Origin and importance come first: for normal (not !important) declarations, user-agent styles lose to user styles, which lose to author styles. Start by listing what matches each element in author styles. For #hero, three declarations compete: the #hero rule, the .panel rule, and the div type rule. For .tag, two rules with the same selector compete. For .alert, three declarations compete: one in base, one in components, and the unlayered one (for <p id="special" class="alert">, the #special rule also matches, making four). For the sidebar paragraph, :where(#sidebar) p and the plain p rule both match.
One more source competes quietly everywhere: the browser default stylesheet, and behind it inheritance. The root element starts from the initial value of color (CanvasText, black in a light colour scheme), and most elements receive color by inheritance from the root; inheritance also passes a parent's color down to children that have no colour of their own. Both lose to any author declaration that matches the element, so for our five elements the fight is entirely among the rules above.
03. Step 2: compare cascade layers
Before specificity is consulted, cascade layers are compared. The @layer reset, base, components; statement at the top declares the layer order once and for all; the physical position of each @layer block in the file then makes no difference. Layers later in that declared list win. Styles outside any layer — the unlayered remainder — beat every layer, because unlayered normal styles are treated as the strongest tier in the author origin. This is deliberate: it lets you override an entire design system or component library without ever editing it, simply by keeping your overrides unlayered.
That settles Case C and Case D immediately. In Case C, the unlayered .alert { color: teal; } beats the rules in base and components. In Case D (#special + .alert), #special has an id selector (1,0,0) but sits in @layer base, so the unlayered .alert rule (0,1,0) beats it before specificity is even checked!
04. Step 3: compare specificity, then source order
Within the same layer tier (or among unlayered rules), declarations are compared by specificity, followed by source order.
Specificity is three columns, compared left to right: the number of id selectors, then the number of class selectors, attribute selectors and pseudo-classes, then the number of type selectors and pseudo-elements. Combinators contribute nothing; they only say which elements match.
- In Case A,
#herois (1,0,0);.panelis (0,1,0);divis (0,0,1). Left to right, (1,0,0) beats the rest:#herowins regardless of where the rules sit in the file. - In Case E,
:where(#sidebar) pis (0,0,1), because:where()and its contents count as zero; only thepcounts. Both:where(#sidebar) pand the plainprule are (0,0,1), an exact tie in specificity, so source order decides: the laterp { color: dimgray; }wins. - In Case B, both
.tagrules are unlayered and both are (0,1,0), an exact tie. Specificity cannot separate them, so source order decides: the second rule,seagreen, wins.
Only when layer and specificity are both equal does source order decide, and later wins.
Here is the check. Open the page, run this in the console, and compare with your predictions:
const pick = (sel) =>
getComputedStyle(document.querySelector(sel)).color;
console.log('A #hero -> ' + pick('#hero'));
console.log('B .tag -> ' + pick('.tag'));
console.log('C .alert -> ' + pick('.alert'));
console.log('D #special.alert -> ' + pick('#special'));
console.log('E sidebar p -> ' + pick('#sidebar p'));A #hero -> rgb(0, 0, 128)
B .tag -> rgb(46, 139, 87)
C .alert -> rgb(0, 128, 128)
D #special.alert -> rgb(0, 128, 128)
E sidebar p -> rgb(105, 105, 105)Read the colours back: A is navy (the id won), B is seagreen (the later of two equal rules won), C is teal (the unlayered rule won), D is teal again, and E is dimgray (:where() scored zero). Case C is the one that pays for the whole lesson: three rules match .alert, and the winner is decided by position in the layer order, not by specificity and not by file position. Case D is the sharpest edge: an id selector inside a layer loses to a bare class selector outside any layer. The id still matters — but only within its layer. Case E confirms that :where() contributes zero, so both rules are (0,0,1) and the later p { color: dimgray; } wins on source order.
05. Step 4: resolve conflicts without !important
Knowing the order gives you three escalation steps, each reversible and each cheaper than !important:
- Put the override in a stronger position: move it outside all layers (or into a later layer), and let the cascade do the work. This is the intended use of
@layer— a widget's styles go in a layer, your overrides stay unlayered. - Match or lower specificity: drop parts that add weight you do not need —
:where()is ideal for defaults that must stay overridable. - Rely on source order: when two rules should genuinely tie, put the intended winner last and say so in a comment.
Each step keeps the conflict visible in the source. !important hides it: the declaration jumps to a separate tier, !important beats !important only by specificity and order again, and important declarations inside layers reverse layer order — so the tool people reach for to end a cascade war usually escalates it. Reserve it for genuine utility escape hatches, and document those.
06. Check your understanding
07. Apply it
In the stylesheet you started for your article page, add a deliberate conflict: give one heading a colour through an id rule and another colour through a class rule, then predict the winner and check it in DevTools. Next, restructure the file into @layer base, components; — base typography and the reset in base, the rest in components — and confirm nothing visible changed, which is the point: layers should reorganise precedence, not change the design. Finish by taking the ugliest override you have and moving it to the strongest honest position instead: unlayered, minimal specificity, last. If you feel the urge to type !important, write a comment saying what you were overriding and why the cascade could not express it.
08. Review prompt
Without looking back, write out the full order the cascade applies to two competing normal author declarations: origin tiers, layers, specificity, source order, inheritance. Compute the three specificity columns of :where(#site) nav a:hover from memory. Then explain, in one sentence each, why a long chain of type selectors loses to a single class, why unlayered styles beat every layer, and why !important tends to spread through a stylesheet once it appears.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.