Go Back

How to win the z-index wars

Posted: 

This is going to be a disappointing answer - don't fight them in the first place.

I recently saw what I thought was the funniest and most poignant example of the z-index wars.

z-index: calc(9e999);

I don't even know if that works since the maximum z-index value is 2147483647. I had to look up what 9e999 represents in Google. Now I'm not sure this is true for CSS but:

9e999 or other overflow number is SQLite representation of infinity.

Infinity! Ha!

But seriously, have a z-index plan

The one way to avoid these wars is to have a plan. Define specific z-index values that represent various levels of your site. That way you always know where something should go and how to get above it without resulting to an infinity equation.

This article on Smashing Magazine has some great ideas of how you can setup systems to deal with z-index - https://www.smashingmagazine.com/2021/02/css-z-index-large-projects/

Also, take a look at the z-index systems of some popular design systems.

Modifiers

Maybe my favorite idea from the z-index article is the idea of before and after modifiers.

It may seem silly to create a css variable that is literally 1 and -1, but think code readability.

--z-index-above: 1;<br>--z-index-below: -1<br><br>.myClass {<br> z-index: calc(var(--z-index-header) + var(--z-index-below));<br>}

I'll admit, it is a little verbose, but it's super obvious what is happening.

Make z-index peace, not z-index war!