Day 43: grouping layers
posted on
It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.
Cascade layers can be grouped by nesting layer rules.
If you work on a large style sheet, you might want to create cascade layers to group different types of declarations. In order to give your layers even more structure and control, you can also group declarations within layers.
Consider the following example. We have a layer for reset styles, base styles, components, and theming.
@layer reset {
body {
margin: 0;
}
}
@layer base {
body {
font-size: 1.6rem;
}
}
@layer components {
p {
border: 1px solid;
}
}
@layer theme {
p {
border-color: red;
}
}
There's nothing wrong with that, but it might make sense to group similar layers. For example, you could group reset and base styles and component and theme styles.
@layer base {
@layer reset {
body {
margin: 0;
}
}
@layer defaults {
body {
font-size: 1.6rem;
}
}
}
@layer components {
@layer structure {
p {
border: 1px solid;
}
}
@layer theme {
p {
border-color: red;
}
}
}
The same rules in terms or prioritization that apply to root layers also apply to nested layers. This adds more complexity to your style sheets, but it also gives you fine-grained control over specificity.
Nesting layer may seem to be overkill, and it probably is for many sites, but it will make more sense once we talk about ordering layers.
Further reading
- Day 37: cascade layers
- Day 40: unlayered styles
- Day 46: ordering layers
- Day 49: layering entire style sheets
- Day 52: multiple layer lists
- Day 55: anonymous layers
- Day 58: ordering nested layers
- Day 64: the revert-layer keyword
- Day 68: cascade layers and browser support
- Day 74: using !important in cascade layers
- A Complete Guide to CSS Cascade Layers
Overview: 100 Days Of More Or Less Modern CSS