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