Cascade Layers
The CSS layers are supported in all browsers using the @layer. These are particularly useful if using resets or a framework like Bootstrap.
The important thing to remember is that styles placed inside a layer will have their specificity reduced relative to styles that are not in a layer.
Basic syntax
This is straightforward. Come up with a name for your layer, put it after the @layer declaration and then everything within the curlies will be part of that layer.
@layer base {
* {
box-sizing: border-box;
}
}
You can redeclare the same layer at multiple places in your CSS.
Two ways of setting up layers
1. Layer order
The way that layers are ordered in the CSS file sets the specificity. The lower down a layer is first declared, the more specificity it will have.
If there is only one @layer layer that will have lower specificity than any CSS not in an @layer layer. Unlayered CSS always has the highest specificity.
@layer one {
h2.red-text {
color: red;
}
}
/* layer two has higher specificity that layer one */
@layer two {
h2 {
color: blue;
}
}
2. List the order
You can use a comma separated list at the top of your stylesheet to define the order. Here layer one has the least specificity and base has the most.
@layer one, two, base
This method makes it very easy to change the layer order.
Using !important
When you use !important on something it switches the specificity from the layer it’s on to the highest layer. This means that if you use !important on the same property in a higher layer the !important on the lower layer will still beat it.
One more advantage ..
I find cascade layers are also handy in text editors for folding sections of code out of the way. Folding works in various apps from VS Code to online editors like Codepen or JS Fiddle by clicking on the little arrows in the left margin. With layers you can hide large sections of code creating focus on the code you’re actually working on.