Never lose a z-index battle again

posted on

Recently, I learned about numeric keywords. Since I was terrible in school, I didn't know what to do with them, but when I saw infinity, I immediately thought of a great use case.

According to the spec, the infinity keyword in the calc() function can be used to indicate the largest possible value of something since an infinite value gets clamped to the allowed range.

For example, you can set an element's largest possible inline size.

CSS

button {
  inline-size: calc(infinity * 1px);
}

Of course, that's not the great use case I'm talking about. Infinity can be super helpful when you want to ensure an element is at the top of the z-axis.

HTML

<button class="a">A</button>
<button class="b">B</button>

CSS

button {
  position: absolute;
}

button.a {
  z-index: calc(infinity);
  background: green;
}

button.b {
  z-index: 2147483646;
  background: blue;
}

You can see how the first button with calc(infinity) set as the z-index is above the button with z-index: 2147483646;. 2147483646 is not an arbitrary number; it's the second-largest possible z-index. A z-index can be any signed 32-bit integer value, ranging from −2,147,483,648 through 2,147,483,647.

If you change the value of the second button to 2147483647, it's on top of the first button because 2147483647 and infinity are the same in this case and the second button comes later in the document.

button {
  position: absolute;
}

button.a {
  z-index: calc(infinity);
  background: green;
}

button.b {
  z-index: 2147483647;
  background: blue;
}

Changing the z-index to calc(infinity + 1) or 2147483648 doesn't make a difference because we've already reached the limit with 2147483647 or calc(infinity).

button {
  position: absolute;
}

button.a {
  z-index: calc(infinity + 1);
  background: green;
}

button.b {
  z-index: 2147483647;
  background: blue;
}

Credit for the title of this blog post goes to Will Boyd