DEV Community

Cover image for Refactoring z-index
Henrik Sommerfeld
Henrik Sommerfeld

Posted on • Edited on • Originally published at henriksommerfeld.se

Refactoring z-index

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
};

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay