Control CSS Specificity with @layer (No !important)
Controlling specificity without !important
The old way was stacking more specific selectors or throwing !important. @layer lets you decide order without fighting specificity.
The old hack vs the modern fix
View demo.card .title {
font-size: 1rem;
}
.page .card .title {
font-size: 1.25rem;
}
.page .card .title.special {
color: red !important;
}
/* More selectors or !important to win */@layer base, components, utilities;
@layer utilities {
.mt-4 {
margin-top: 1rem;
}
}Cascade layers browser support
Live demo
Why the modern way wins
Order over specificity
Later layers win. No need to make selectors more specific to override.
Predictable cascade
base, then components, then utilities. Same order every time.
No !important
Utilities can override components with a single class. Clean and explicit.
- Lines Saved
- N/A
- Clear structure
- Old Approach
- !important, specificity
- Selector arms race
- Modern Approach
- @layer order
- Declared priority
How it works
Previously you made selectors more specific (e.g. .page .card .title) or used !important to force overrides. That led to specificity wars and hard-to-debug styles.
@layer base, components, utilities defines the order. A later layer wins no matter how specific the selectors in earlier layers are. Specificity only decides between rules in the same layer. Unlayered styles beat every layer, so put your component styles in a layer too. Put resets in base, components in components, and utility classes in utilities. No !important, no long selectors.