Auto-Generating Z-Indexes with SASS

Skipping to and from dozens of different lines and files within your project to ensure a correct z-index order can be cumbersome, error-prone and time consuming. Wouldn’t it be better if we could keep track of our z-indexes, all in the one place? Sure, we can keep them all in a block of code at the end of our main file, but we still need to manually fiddle with numbers. There’s an even better way with SASS.

Z-index management is one of the most useful things that SASS gives us. We no-longer need to fiddle with numbers, and the order is presented in a direct, visual way. Introducing the mixin:

@mixin u-z-index
    $me: "#{&}";
    $z-val: index($z-list, $me);
    z-index: $z-val * 10 + 100;

This is how it’s used:

    @include u-z-index;

Managing Z-indexes is now as simple as adding the mixin to your element, then adding the selector to the list within the mixin. You can change the z-index order by moving the selector lines around in the list. The final z-index will be a result of its index within the list, times 10, plus 100. I start my lists at 110 as there are some javascript libraries that auto-generate z-indexes between 1 and 100. You can remove that part if you don’t need it.

This functionality is achieved by others in different ways, you should check them out too and decide what would work best for your project. Remember, keep it simple unless you can justify the need for added complexity.

Other examples:

Some of these other examples add z-index ‘categories’ and assign each element to a category. I prefer to do without categories and ensure that each element has a different z-index. These techniques are a great example of how to use new technology to improve the quality of code.