Henrik Sommerfeld
Menu

Refactoring z-index

Handles for standing subway passengers, from close to far away.

Photo by Sabri Tuzcu on Unsplash. Creating depth with z-index. Mine is most important, so I set it to 999999.

Ever found a z-index of 999 in CSS and wondered if there really are 998 other elements below it?

One time I even stumbled upon a z-index of 2147483647

One time I even stumbled upon a z-index of 2147483647. I thought that number looked familiar, “isn’t this Int32 max value? 🤔” Yes, a google search later my suspicion was confirmed: the highest z-index you can use is the maximum value of a 32 bit integer.

But, even if you can use really high numbers for z-index, why should you? The answer is simple: you shouldn’t! High numbers are unnecessary and just makes it harder to see what’s higher and lower, the difference between 99999 and 148851 can be hard to spot a glance. So, how can we make something better?

My refactoring

The first thing I did in the code base I was working on, was to collect all the indexes in a constants file. We were using styled components, so my example is in javascript, but of course the same thing can be done in Sass.

export const zIndexes = {
  AlertBox: 10,
  ModalOpacity: 100,
  PresentationContainer: 745,
  HamburgerMenu: 999,
  MenuOpacity: 999,
  Arrows: 9999,
  MenuWrapper: 12500,
  FullScreenButton: 99999,
  ProgressBar: 999999
};

Note that I ordered them by ascending index. By putting all z-indexes in the same file, we have a great overview of them. The place I copied the values from, are now referencing a constant instead of having the actual value. I think this is also good from a readability standpoint - you don’t have to care what the value is when looking at the styles for a component/class.

Next step is to take those numbers down to something simpler. If we have a new element that needs a value between the existing ones, we can just re-assign all of them, no biggie.

export const zIndexes = {
  AlertBox: 1,
  ModalOpacity: 2,
  PresentationContainer: 3,
  HamburgerMenu: 4,
  MenuOpacity: 4,
  Arrows: 5,
  MenuWrapper: 6,
  FullScreenButton: 7,
  ProgressBar: 8
};
No matching posts found. You can use wildcards and search only in titles, e.g. title:iot
Loading search index, please try again in a few seconds.
Index has completed downloading. Please search again.