Manage z-index values with Sass

Z-Index values in your CSS can become a chore to manage on any size project. Rather than setting arbitrary rules for determining your z-index values we can use Sass to do it for us.

Maps

A Sass map is an array that can be associative or multidimensional and resembles JSON. Maps must always be encased in parenthesis.

$map: (value1, value2);

$assoc-map: (
  key1: value1,
  key2: value2,
);

$multi-map: (
  sub-map-1: (
    key1: value1,
    key2: value2
  ),
  sub-map-2: (
    value1,
    value2
  )
);

Managing z-index with Maps

There are a couple options for using maps to manage our z-index values.

Using Associative Maps

If you want to maintain total control over your z-index values you can use an associative map.

$zmap: (
  "element1": 9001, // IT'S OVER 9000!!!
  "element2": 500
);

Using the above map we can access our z-index values with map-get.

.element1 {
  z-index: map-get($zmap, "element1");
}

// Outputs
.element1 {
  z-index: 9001;
}

If we don't want to type map-get all the time we can wrap it in a function.

@function zidx($elm) {
  @return map-get($zmap, $elm);
}
Using the Array Index

This is my preferred method. If we don't want to manage the numbers we can leverage the array index.

When using the array index it is important to remember that the later elements will be above the earlier elements since they have a higher index. In Sass the index value starts at 1.

$zmap: (
  "bottom-element",
  "middle-element",
  "top-element"
);

Using the above map we can access our z-index values with index.

.top-element {
  z-index: index($zmap, "top-element")
}

// Outputs
.top-element {
  z-index: 3;
}

Like before we can also wrap out index call in a function.

@function zidx($elm) {
  @return index($zmap, $elm);
}