If you've ever worked on a medium to big project I'm sure you know how painful it is to work with z-index
CSS rules. What number should I use to put this component on top of another, like 1
, 5
, 10
, 999
or even 9999
?
The solution is creating variables with meaningful names for z-index values, put them in the same place and refer to them wherever you need them. Here's an example in pure CSS, but you can use the same concept in any styling tool you're currently using
:root {
--z-index-toolbar: 1;
--z-index-sidebar-backdrop: 2;
--z-index-sidebar: 3;
--z-index-modal-backdrop: 4;
--z-index-modal: 5;
}
.toolbar {
z-index: var(--z-index-toolbar);
}
.sidebar-backdrop {
z-index: var(--z-sidebar-backdrop);
}
.sidebar {
z-index: var(--z-sidebar);
}
.modal-backdrop {
z-index: var(--z-modal-backdrop);
}
.modal {
z-index: var(--z-modal);
}
What really matters about z-index is its relative value and not the absolute one, so it makes sense to have all indices stored in the same place as variables and quickly compare and edit them.
Photo by Héctor J. Rivas on Unsplash
Top comments (0)