Cascade layers
Learn layered cascading with the @layer rule.
Layers with @layer
The @layer statement gathers styles into named layers. You set the order of layers; the browser then looks at layer order first, then specificity inside the layer. "Who wins" is bound to a clear hierarchy.
Example: declare @layer base, components; once at the top. Then place styles with @layer components { .card { ... } }. The components layer overrides base; one line sets the order.
How is layer order set?
The first occurrence locks the order. If you write @layer base, components, utilities;, that order holds for the whole file: base at the bottom, utilities at the top. Later writing @layer base { ... } still leaves base at the bottom.
Unlayered styles — declarations not wrapped in @layer — always beat every layer. So you might think unlayered styles are the strongest. Keep a style unlayered only when it really must beat everything else.
Specificity inside a layer
Inside the same layer, ordinary cascading applies: higher specificity wins, ties go to the later one. In @layer components { #main .card { ... } .card { ... } } the first declaration wins because its specificity (1, 1, 0) is higher.
Between different layers, only layer order matters. Even #main inside base loses to .card inside components; the components layer is higher. Layer order overrides specificity.
Exercise Set up a two-layer skeleton
Add the @layer base, components; order statement at the top. Then inside an @layer base block, set margin: 0 on body. Finally, inside an @layer components block, set padding: 1rem on .card.
Show example solution
/* add the layer skeleton */
@layer base, components;
@layer base {
body {
margin: 0;
}
}
@layer components {
.card {
padding: 1rem;
}
}
Test yourself
-
Which declaration wins?
@layer base, components; @layer base { .card { color: black; } } @layer components { .card { color: navy; } }- color: black — base was written first
- color: navy — components overrides base
- color: navy — due to specificity
- color: black — base is stronger
Show answer
color: navy — components overrides base — Correct. The components layer comes after base; with the order base, components, components wins.
-
Name the @layer block
@layer ____ { body { margin: 0; } }Show answer
@layer base { body { margin: 0; } } -
Match each cascade layer form to its meaning
- @layer a, b;
- Layer order
- @layer a { }
- Style block
- a
- Layer name
- a, b
- Name list