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;
}
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);
}
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;
}
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)
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 โ๏ธ
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.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.
Very useful and time saving ! thanks !
We've been using this for a good few years ๐