How to deal with z-index?

Geschreven op 10 juli 2019 door Jordi Fuite
.overlay {
  position: absolute;
  z-index: 999;
}

.header {
  position: fixed;
  z-index: 9999;
}

Does this sound familiar? As a front-end developer I encountered these z-index rules very often. If you have a new element that has to overlap all other elements, many people quickly add a 9 to their highest z-index.

This was also the case at Your Source until a year ago. Then we found out that this can also be done differently. Why can you organize everything except your z-index?

We came to the conclusion that this is possible. Using SASS and SCSS, all sorts of smart features have suddenly become possible and we can get our CSS structured.

Currently, our z-index values do not exceed 10, without having much work to organize them. We use our so-called "z-function": A function in SCSS which uses a list and determines a z-index by using the index of your value. That way we can easily add and manage z-index values.

$z-indexes: (
  'header',
  'overlay',
  'body',
);

@function z($name) {
  $z-index: () !default;
  @if index($z-indexes, $name) {
    @return (length($z-indexes) - index($z-indexes, $name)) + 1;
  }

  @else {
    @warn 'There is no item "#{$name}" in this list; choose one of: #{$z-indexes}';

    @return null;
  }
}

body {
  position: relative;
  z-index: z('body'); // z-index: 1;
}

.overlay {
  position: absolute;
  z-index: z('overlay'); // z-index: 2;
}

.header {
  position: fixed;
  z-index: z('header'); // z-index: 3;
}

Reactie toevoegen

Plaats hier uw naam.