Hilde Skjølberg
Written by Hilde Skjølberg
Published 2015-02-16

Clean and simple Z-index with SASS lists

So.. Z-index. Ever used it on a rather large scale site before? Or in a CSS environment that you don’t really know inside out? What number did you set? Did you make it really, really high just to be sure? Ever used z-index: 100003? Or 99999999?

Highest z-index was an astonishing 999999999999999999999999999 or 9.99e26. With a default key repeat on OS X, this would take 3 seconds of holding down 9 to type.

QuickLefts 2014 CSS report

You don’t do that, right? Perhaps you rather build systems with levels set in hundreds or thousands, to be able to sneak in future elements? The oddball z-index: 1005; here and there?

For my latest project I used a rather simple trick in SASS that got me out of this potential mess, and I didn’t even set a single number. SASS took care of that for me!

Entry image

The solution is using lists and referencing indexes in SASS. Here’s the trick:

Define a list of element types you’ll be stacking, from the bottom to the topmost element. Use names that will make sense to you (or others) when you go back to the code six months from now. I usually place the list in my _variables.scss file, for easy reference.

According to this list, a popover will be placed above a message-bar, which will be stacked above a modal, which will be stacked above a tooltip, which will be placed above the menu-bar.

When I’m styling my popover, I define the z-index like this:

.. which means «what number is “popover” in the list called “z-elements”»?

The answer is “5”, and here’s the resulting CSS:

What happens when a new layer comes along? Someone tells you to dig up this old code and insert a new ad-element to be visible even when the modal is triggered, but below any possible message bars. Easy – you just add the element to the list, and all the numbers will be adjusted accordingly:

In the compiled CSS, the new ad will get a z-index of 4, message-bar will go from 4 to 5, and popovers will now have a z-index of 6:

Easy peasy, right?


– Lists can be separated with spaces or commas. I prefer using commas.
– SASS indexes start at 1, not 0 (which differs from JS etc.).
– See more about scaling this solution across stacking contexts, error handling etc. in this Smashing Magazine article.

Written by Hilde Skjølberg
Published 2015-02-16