Managing Specificity Chaos
Cascade layers are one of CSS's most powerful innovations. They allow grouping styles into " layers " and explicitly specifying which layer is more important, regardless of selector weights within them.
Why Do We Need This?
Imagine you're using a third-party style library. You want to change the button color, but the library's selector is so complex you have to write a long chain or use !important. The @layer solves this.
How to Use:
/* Define layer order. Last in list = highest priority */
@layer reset, base, layout, components;
@layer components {
.btn {
background: blue; /* Even if this is just a class... */
}
}
@layer base {
button {
background: red !important; /* ...styles from base layer are weaker than components */
}
}
Important
Styles OUTSIDE layers always have priority over any layers (except cases with !important).
Tip
Use layers to separate " base " site styles from specific component styles.