Layers, sublayers, and scope
Declaring layers at the top of our file
One thing that could come in handy is to declare our layers at the top of our CSS file like so:
@layer reset, base, layout, components, utilities;
This sets the order of the layers, and would allow you to put them in any order lower down in your file, if you'd prefer.
For example, I like having my :root
at the top of my file so that I can quickly reference my custom properties if I need to.
By declaring the order of the layers first, I can then use my base
first, and have it still be higher precedence than the reset
.
Sublayers
If you're enjoying using @layer
in this project, you might consider using nested layers as well.
Nested layers act like a mini-set of layers, within the larger layer they are in.
For example:
@layer base {
@layer root {
:root {
/* custom props here */
}
}
@layer general-styling {
body {
/* ... */
}
/* all the general styling here */
}
}
Sublayers work in a similar way to layers, in terms of how they impact the cascade, but within their individual layer only.
It can be a useful tool for organization, but on a smaller project like this one, it probably isn't required.
Don't use layers as a scoping tool
The one thing you want to avoid when using @layer
is using them as a scoping tool, because they don't work that way, and it could potentially get you back into specificity issues depending on the order of things.
For example:
@layer components {
@layer cards {
.card.accent {
background: purple;
> .button {
background: yellow;
}
}
}
@layer buttons {
.button {
background: purple;
}
}
}
Despite the high specificity of the button selector in the card layer, the background of the button will be purple.
Now, there are more issues here than the lower layer winning, but it's a simple example to highlight how things can go wrong.
Layers are for creating layers of specificity, and helping us stay a bit more organized.
If you want to have styles for a specific element, you could consider using @scope
, but it's a more advanced feature.