ap

Managing the z-index with Sass

As it goes, the z-index can quickly become a messy thing to control, particularly in a large code-base. Fortunately, Sass can be used to make it ever so slightly more manageable.

Rather than having multiple references to our z-index values spread out across the code-base, we instead bring all of these in to one place. We list all of our elements in to a index, which allows us to define the order depending on the position of the element in the list.

One of the biggest benefits of this other than maintainability, is that it removes the need to have elements with z-index's of 99999.

$z-stack: site, globalHeader, modal, modalOverlay;

Then, where ever we need to add a z-index, we can reference this variable like so:

.global-header {
  z-index: index($z-stack, globalHeader);
}

.modal {
  z-index: index($z-stack, modal);
}

Which would generate:

.global-header {
  z-index: 2;
}

.modal {
  z-index: 3;
}