Lesson 2 of 9 · 22m
Cascade Layers: Architecture You Can Enforce
@layer gives you a specificity override — base styles always lose to components, utilities always win, and the order is declared in one place instead of being emergent behavior.
Cascade layers are the most important CSS feature of the last decade and most teams still aren't using them, which is a shame because they solve the exact problem that makes large CSS codebases miserable. Before layers, the winner of any specificity fight was accidental — it depended on specificity inflation and import order, neither of which anyone chose deliberately. Layers make precedence declared architecture.
The mechanism
@layer reset, base, components, utilities;
@layer reset {
* { margin: 0; }
}
@layer base {
body { font-family: system-ui; line-height: 1.5; }
a { color: #2563eb; }
}
@layer components {
.card { border: 1px solid #e5e7eb; border-radius: 8px; }
.card a { color: inherit; } /* beats base's `a` even though specificity ties */
}
@layer utilities {
.text-center { text-align: center; }
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
}The layer order is established by the first line — @layer reset, base, components, utilities; — and any rule in components beats any rule in base no matter the specificity. .card a (0,1,1) beats a (0,0,1) not because of specificity, but because layers are decided before specificity is even consulted.
The two rules that matter in production
Unlayered styles beat layered styles. If a legacy stylesheet has plain .btn { ... } and your new architecture puts .btn in @layer components, the legacy rule wins — by design, so you can migrate incrementally. Wrap legacy code in @layer legacy early, or your migration will silently invert precedence.
!important inverts layer order. !important declarations in earlier layers beat !important in later ones. In practice: don't use !important inside layers except for utilities, and even then know what you're doing.
Import order and third-party CSS
@layer vendor, base, components, utilities;
@import url("vendor/normalize.css") layer(vendor);
@import url("./base.css") layer(base);You can layer entire files at import time. This is the correct way to cage a CSS framework or a third-party widget stylesheet: force it into an early layer and your component styles will always beat it without specificity wars.
Field notes
- Put the layer-order declaration line at the very top of your entry CSS file, before everything else. First mention wins — if a component file mentions
@layer utilitiesbefore your order declaration, the order is already fixed wrong. - Layers are supported in all modern browsers since 2022. If you support IE11 you have bigger problems than cascade layers.
- DevTools shows the layer a rule belongs to in the Styles pane — check it when something "should" win and doesn't; unlayered-vs-layered is the usual culprit.
Was this lesson helpful?