By | August 22, 2017
z-index

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@mixin u-z-index
{
    $z-list:
        '.w-home-banner-arrows'
        '.w-home-banner-pager'
        '.w-home-banner-ad'
        '.w-carousel-previous'
        '.w-carousel-next'
        '.w-bottom-bar-categories-box'
        '.w-bottom-bar-categories-box-sub-category'
        '.w-middle-bar-classifications-box'
        '.w-middle-bar-search-toggle[aria-pressed=true]::after'
        '.w-middle-bar-search-box'
    ;
    $me: "#{&}";
    $z-val: index($z-list, $me);
    z-index: $z-val * 10 + 100;
}

This is how it’s used:

1
2
3
4
5
.w-bottom-bar-categories-box
{
    @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:

https://www.sitepoint.com/better-solution-managing-z-index-sass/

https://www.smashingmagazine.com/2014/06/sassy-z-index-management-for-complex-layouts/

https://jonsuh.com/blog/organizing-z-index-with-sass/

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.

Leave a Reply

Your email address will not be published. Required fields are marked *