Organize and control CSS specificity using cascade layers to manage style precedence without relying on specificity hacks.
Explanation
@layer: Creates named layers that control cascade order independently of specificity.- Earlier defined layers have lower priority than later layers.
- Unlayered styles have highest priority by default.
- Helps prevent specificity conflicts in large codebases and design systems.
Usage
To organize CSS with predictable cascade control:
/* Define layer order upfront */
@layer reset, base, components, utilities;
/* Reset layer - lowest priority */
@layer reset {
* {
margin: 0;
padding: 0;
}
}
/* Base styles */
@layer base {
body {
font-family: system-ui;
line-height: 1.5;
}
}
/* Component styles */
@layer components {
.button {
padding: 0.5rem 1rem;
background: blue;
}
/* Low specificity but still wins due to layer order */
.button {
background: var(--primary);
}
}
/* Utilities - highest priority */
@layer utilities {
.bg-red { background: red !important; }
}