Learn the concept
Cascade Layers (@layer)
Cascade layers (@layer) let you group CSS rules into named layers with explicit priority ordering. Rules in later-declared layers override earlier ones regardless of selector specificity, giving you architectural control over which styles win without resorting to !important or specificity hacks.
The specificity problem:
In large projects, specificity wars lead to overly-specific selectors, !important overuse, and fragile CSS. Cascade layers solve this by adding a new level to the cascade.
How layers work:
@layer reset, base, components, utilities;Layer priority (lowest to highest):
Use cases:
/* 1. Declare layer order (priority: left-to-right) */
@layer reset, base, components, utilities;
/* 2. Add rules to layers */
@layer reset {
* { margin: 0; padding: 0; box-sizing: border-box; }
}
@layer base {
body { font-family: system-ui; line-height: 1.5; }
a { color: var(--color-link); }
}
@layer components {
.button {
padding: 0.5rem 1rem;
border-radius: 0.5rem;
background: var(--color-primary);
}
/* Even with low specificity, this beats @layer base */
}
@layer utilities {
.hidden { display: none; }
.sr-only { /* screen-reader only styles */ }
/* These override components despite simple selectors */
}By organizing styles into explicit layers (e.g., reset, base, components, utilities, themes) to prevent specificity conflicts and simplify maintenance in multi-developer environments.
By placing vendor styles in a lower-priority layer, ensuring that your custom styles can easily override them without resorting to `!important` or overly specific selectors.
Where the order of style application is guaranteed by layer declaration, allowing for easier reasoning about styling rules and consistent visual outcomes.
Implement a web page with multiple themes (light/dark/custom) using CSS cascade layers to manage and switch between different style sets effectively.
Integrate a third-party component library (e.g., a UI framework) into a project using cascade layers to seamlessly apply custom branding and overrides.
Large design systems like Salesforce's often deal with immense CSS complexity. Cascade layers provide a powerful mechanism to manage style precedence and ensure consistency across a vast number of components and applications.
WordPress themes and plugins often struggle with CSS conflicts due to their modular nature. Cascade layers can offer a robust solution for theme and plugin developers to organize their styles and prevent unintended overrides, ensuring better interoperability.