When: Use @layer to control cascade order across resets, base styles, themes, and
utilities—especially in larger projects or teaching code organization.
Where: Component libraries, multi-author codebases, or any site where predictable overrides
matter.
How: Declare layer order once (e.g., @layer reset, base, theme, utilities;), then
place rules inside named layers. Later layers win unless specificity or importance changes that.
This card and button are styled via layered CSS. Try toggling classes to see utilities override base/theme.
Reset → Base → Theme → Utilities. Utilities add rounded corners and shadow on top.
@layer reset, base, theme, utilities;
@layer reset {
* { box-sizing: border-box; margin: 0; padding: 0; }
}
@layer base {
body { color: #222; }
.card { border: 1px solid #ccc; background: #fff; }
}
@layer theme {
body { background: lavender; }
.card { background: #fffafc; border-color: #e0b3d6; }
.btn { background: #f0e6f6; border-color: #c8a2c8; }
}
@layer utilities {
.rounded { border-radius: 12px; }
.shadow { box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
}
/* HTML
<div class="card rounded shadow">
<h3>Layered card</h3>
<p>Reset → Base → Theme → Utilities</p>
<button class="btn">Layered button</button>
</div>
*/