patterncssTip
@layer for managing cascade specificity and ordering
Viewed 0 times
@layercascade layersspecificityCSS cascadeoverridepriority
Problem
Third-party CSS (resets, component libraries) conflicts with custom styles, and increasing specificity to override styles leads to a specificity arms race that is hard to maintain.
Solution
Use @layer to explicitly control the cascade order. Styles in later layers win over earlier layers, regardless of specificity:
/* Declare layer order first (lower layers = lower priority) */
@layer reset, base, components, utilities;
/* Import third-party into a specific layer */
@import url('normalize.css') layer(reset);
/* Layer styles */
@layer base {
a { color: blue; } /* specificity: 0-0-1 */
}
@layer components {
a { color: red; } /* wins over base layer a, even same specificity */
}
@layer utilities {
.text-green { color: green; } /* wins over all previous layers */
}
/* Unlayered styles win over all layers */
a { color: purple; } /* this wins over all @layer styles */Why
@layer introduces a new origin in the cascade above specificity. Styles in a higher layer win regardless of selector specificity within a lower layer. This allows libraries to be safely wrapped in low-priority layers.
Gotchas
- Styles not in any layer (unlayered) always win over layered styles — regardless of specificity.
- The order of @layer declarations (not definitions) determines priority — declare all layer names at the top of the stylesheet.
- Nesting layers is supported: @layer components.card { }.
- !important interacts with layers in the reverse order — !important in a lower layer wins over !important in a higher layer.
Context
Large CSS codebases, design systems, or projects that mix third-party CSS with custom styles.
Revisions (0)
No revisions yet.