Sub topic 13
Debugging Layers and Avoiding Common Pitfalls
This chapter assumes you know selector specificity and source order, the block and statement forms of @layer, how unlayered styles and !important interact with layers, and how to inspect applied styles in browser DevTools. Here you will use that knowledge to find out why a rule loses and to avoid the mistakes that cause most layer bugs.
The Debugging Model
When two declarations conflict, the browser compares them in a fixed sequence and stops at the first step that separates them:
- Origin and importance (user agent, user, author, and whether
!importantis set). - Inline styles.
- Layer order.
- Specificity.
- Order of appearance.
Specificity only matters when both declarations are in the same layer, or both are unlayered. A rule with a very specific selector can lose to a rule with a bare element selector if the second rule sits in a higher-priority layer. Debugging a layer problem therefore means working through the steps in that order. Don't start by raising specificity.
Reading DevTools
Current Chrome, Edge, and Firefox show the layer name next to each rule in the Styles or Rules panel, for example @layer components. Unlayered rules have no such label. Chrome and Edge also offer a view of the layer tree. Use these steps:
- Select the element and find the declaration that is applied. Struck-through declarations lost.
- Read the layer label on the winning rule and on the losing rule. No label means unlayered.
- If the labels differ, compare the layers' positions in the order, and ignore specificity.
- If both labels are the same, or both are missing, compare specificity and source order as usual.
Layer order is easy to get wrong when stylesheets come from several files. The following script prints the layer rules in each same-origin stylesheet. Paste it into the console.
function listLayers(rules, prefix = "") {
for (const rule of rules) {
if (rule instanceof CSSLayerStatementRule) {
console.log(prefix + "order statement:", rule.nameList.join(", "));
} else if (rule instanceof CSSLayerBlockRule) {
console.log(prefix + "block:", rule.name || "(anonymous)");
listLayers(rule.cssRules, prefix + " ");
}
}
}
for (const sheet of document.styleSheets) {
try {
listLayers(sheet.cssRules);
} catch {
// Cross-origin stylesheets cannot be read.
}
}The output lists layer rules in the order the browser parsed them. The first time a layer name appears in that list is its position in the layer order.
Pitfall 1: Layer Order Is Set by First Appearance
A layer's position is fixed by the first place its name appears. Reopening the layer later adds rules to it but does not move it. If a file mentions components before base, then components ranks lower than base, even when you meant the opposite.
@layer components {
.btn { background: teal; }
}
@layer base {
button { background: gray; }
}For <button class="btn">, the button is gray. components appeared first, so base has higher priority. The fix is one statement at the very top of the first stylesheet that loads:
@layer base, components;
@layer components {
.btn { background: teal; }
}
@layer base {
button { background: gray; }
}Now the button is teal, and the order of the blocks below the statement no longer matters.
Pitfall 2: Unlayered Styles Beat Layers
Unlayered normal declarations beat layered normal declarations, whatever the specificity. The usual cause is a legacy stylesheet that was never put into a layer, or an @import with no layer() part. Everything in that stylesheet then outranks your whole layer system.
@layer base, components;
@layer components {
.card .title { color: black; }
}
h2 { color: gray; }For <h2 class="title"> inside a .card, the heading is gray. The h2 rule is unlayered and has lower specificity, yet it wins.
There are two fixes. You can move the legacy CSS into a layer, ideally the lowest one. Or you can accept that unlayered CSS is a high-priority zone and keep only deliberate overrides there. Moving everything into layers is the safer choice, because it makes DevTools output consistent.
Pitfall 3: Forgetting That `!important` Reverses Order
For normal declarations, later layers win. For !important declarations, earlier layers win, and unlayered important declarations rank below every layered important declaration.
@layer base, overrides;
@layer base {
a { color: red !important; }
}
@layer overrides {
a { color: blue !important; }
}Links are red. The reversal follows from the design: an early layer such as a reset can use !important to protect a rule that no later layer may change.
@layer base {
a { color: red !important; }
}
a { color: blue !important; }Links are still red here. The unlayered important declaration is the weakest of the important ones.
Practical advice: avoid !important in your own layered CSS. If you see it in DevTools, look at the layer it came from before deciding what to do.
Pitfall 4: `@import` Placement and Missing `layer()`
An @import rule must come before all other rules, except @charset and @layer statements. If you put it after a normal rule, the browser ignores it. An @import without layer() creates unlayered styles (see Pitfall 2).
@layer vendor, site;
@import url("vendor.css") layer(vendor);
@layer site {
.btn { padding: 0.5rem 1rem; }
}This is correct. The statement comes first, then the import, then the blocks. This next version is broken:
body { margin: 0; }
@import url("vendor.css") layer(vendor);The @import is ignored because the body rule precedes it. If styles seem to be missing entirely, check the DevTools Network panel to see whether the file was ever requested.
Pitfall 5: Rules Directly Inside a Layer Beat Its Sublayers
Declarations placed directly in a layer, outside any sublayer, behave as if they belong to an implicit sublayer that comes last. For normal declarations, that implicit sublayer beats every named sublayer.
@layer framework {
@layer base, theme;
@layer theme {
p { color: #333; }
}
p { color: crimson; }
}Paragraphs are crimson, even though theme is the last named sublayer. When you reopen a nested layer with dot notation, use the full path, for example @layer framework.theme. Writing @layer theme at the top level creates a different, unrelated layer.
Pitfall 6: Anonymous Layers Cannot Be Reopened
An @layer { ... } block without a name creates a new layer every time. You can't refer to it again, so you can't reorder it or add to it. Its position is set by where it appears relative to the other layers. Use anonymous layers only for code you want to wall off completely. If you may ever need to override or reorder something, give it a name.
Pitfall 7: Assuming Layers Remove Specificity
Layers add a step before specificity. They don't replace it. Inside one layer, #nav a.link still beats .link, and a later rule still beats an earlier one of equal specificity. A common mistake is to move everything into a single components layer and then be surprised that specificity fights return. Split by role, so that cross-role conflicts are settled by layer order and only same-role conflicts depend on specificity.
Pitfall 8: Inline Styles and Reverting
Inline style attributes beat layered normal declarations, so a layer will not override JavaScript-set styles. If you need to roll back to an earlier layer's value for one element, revert-layer does that without raising specificity:
@layer base, components;
@layer base {
button { padding: 1rem; }
}
@layer components {
button { padding: 2rem; }
button.plain { padding: revert-layer; }
}button.plain gets 1rem, taken from base. If no earlier layer sets the property, the value falls back to the origin below, usually the browser default.
Symptom Table
| Symptom | Likely cause | Fix |
|---|---|---|
| A low-specificity rule beats a high-specificity one | The winner is in a later layer, or is unlayered | Compare layer labels in DevTools |
| Your layered CSS never wins against old CSS | The old CSS is unlayered | Put it in the lowest layer |
| Layers appear in the wrong order | An unexpected file named a layer first | Add an order statement at the top of the first stylesheet |
| An imported file has no effect | `@import` is after other rules, or the URL is wrong | Move it up, check the Network panel |
| An `!important` rule wins in an earlier layer | Important order is reversed | Remove `!important`, or move the rule |
| A top-level `@layer theme` does nothing to a nested theme | Dot notation was not used | Write `@layer framework.theme` |
Exercise
A page has the order statement @layer reset, base, components, utilities;. The utilities layer contains .hidden { display: none; }. A legacy stylesheet, imported without layer(), contains .panel { display: block; }. An element has class="panel hidden" and shows up on the page. Why, and what is the cleanest fix?
Show answer
The legacy stylesheet is unlayered, and unlayered normal declarations beat every layered normal declaration, so display: block wins over the utilities rule. The cleanest fix is to import the legacy stylesheet into a layer, for example @import url("legacy.css") layer(base);, placed after the order statement. Then utilities outranks it.
Exercise
Given @layer a, b;, @layer a { p { color: red !important; } }, and @layer b { p { color: blue !important; } }, what color are paragraphs, and why?
Show answer
Red. For !important declarations the layer order is reversed, so the earlier layer a beats the later layer b.
Exercise
A stylesheet starts with @layer components { .btn { color: white; } } and later has @layer base, components;. Does the later statement make base rank below components?
Show answer
No. The layer order was fixed when components first appeared, so components is first and base second. The later statement only introduces base as a new layer after it. base now outranks components for normal declarations. To get the intended order, put @layer base, components; before any block.