DEV Community

Cover image for CSS Hack: "Named Layers"
𒎏Wii 🏳️‍⚧️
𒎏Wii 🏳️‍⚧️

Posted on

CSS Hack: "Named Layers"

The Problem

When elements overlap on a website, the CSS property z-index lets us decide which should be drawn on top.

But this property only uses plain numbers, which will usually appear spread out through countless CSS files.

This is both difficult to keep track of and hard to read.

The Solution

Stop using numbers directly when setting the z-index on a selector. Instead, put something like this at an easy to find spot, like a separate layers.css file:

:root {
   --layer-overlay: 2;
   --layer-floating: 1;
}
Enter fullscreen mode Exit fullscreen mode

Then, when you want to assign one of these "layers" to an element, simply use the custom element as its z-index:

.overlay {
   z-index: var(--layer-overlay);
}
my-floating-component {
   z-index: var(--layer-floating);
}
Enter fullscreen mode Exit fullscreen mode

This way, you can just number your layers starting at one, without having to leave gaps in case you ever want to add something in between. The numbers are now all in one place and easy to update.

Say you want to add a header layer in between the existing two. You just increase the overlay layer to 3 and add the header in between:

:root {
   --layer-overlay: 3;
   --layer-header: 2;
   --layer-floating: 1;
}
Enter fullscreen mode Exit fullscreen mode

Note: This is different from "CSS Layers", which change the order in which rules are applied. Those are "layers" in the cascade, these are "layers" in the rendered webpage.

I've been using custom properties for many years now, and only recently figured out I can just use them to organise my z-indices like this.

Did you think of doing this too? Have you seen it out in the wild? Please leave your thoughts in the comments <3

Top comments (5)

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

I like the names idea, but I can count and in this case I would prefer to use logic over convince. However 9e9 is a very big and valid number you can use to win the z-index war ✌️

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Until you add another element three months later, and don't realise that on some random page the two appear at once and one gets shoved under the other in a really weird way and now you have to go even higher and then another three months later the whole story repeats...

It's kind of like with !important: it works in the moment, but it's not sustainable for longer projects.

Collapse
 
lexlohr profile image
Alex Lohr

This is one of the best uses of CSS variables ever. Not only conveys it semantic meaning, it also allows you to organize your z-index at a single point, which makes it a lot more maintainable.

Collapse
 
codebuddylarin profile image
Niral

Very useful and time saving ! thanks !

Collapse
 
jonrandy profile image
Jon Randy 🎖️

We've been using this for a good few years 👍