Avoiding z-index Nightmares
An easy and scalable way to manage z-index
Throughout my career, in the projects where I've worked, I have never seen an effective way to handle the setting of z-index. It's not uncommon to see z-index: 9999
, and it could even be higher, becoming very unscalable.
An effective way to handle z-index and keep them organized to ensure scalability is to store the values of each element to which we assign a z-index in one central place. It could be an object, but in this case, I will be storing them as CSS Variables.
Then, in each element where we want to assign one of these values, we'll simply do
This way, whenever we need to assign a z-index, it would be enough to refer to these variables to know which element will have a higher priority to be above another.