How to use CSS @layer to organize stylesheets
· Category: HTML & CSS
Short answer
The @layer at-rule lets you define named cascade layers. Styles in later-declared layers lose to earlier-declared layers when specificity is equal, making it easier to manage CSS from third-party frameworks and custom themes.
Details
Define layers at the top of your stylesheet with @layer reset, base, components, utilities;. Then wrap related CSS in @layer base { ... } blocks. Because layers are evaluated before specificity, a low-specificity selector in the components layer will override a high-specificity selector in the base layer.
This is especially useful when importing third-party CSS. You can assign an entire import to a layer: @import url('framework.css') layer(framework);. For organizing component code, you may also want to read about what are JavaScript modules to keep your scripts as modular as your styles.
Tips
- Unlayered styles always win over layered styles, so be intentional about what remains outside layers.
- Use
revert-layerto roll a property back to the value from a previous layer. - Cascade layers are supported in all modern browsers; they are one of the most significant additions to CSS specificity management in years.
- For related layout organization, see What is CSS Grid auto-placement and how does it work.