z-index and Stacking Contexts

The z-index property controls stacking order within stacking contexts. A common mistake is assuming that a very large z-index always places an element above everything else. It does not cross stacking-context boundaries.

Stacking contexts can be created by several CSS conditions, including positioned elements with non-auto z-index, opacity below 1, transforms, isolation, and other properties.

Stacking Contexts and z-index
Layering
.modal {
  position: fixed;
  inset: 0;
  z-index: 1000;
}

.modal__dialog {
  position: relative;
  z-index: 1;
}
💡 A modal can establish a deliberate layering hierarchy, but application-wide z-index values should be organized rather than arbitrarily increased.
Key Takeaways
  • z-index is meaningful within stacking contexts.
  • Create a documented layering scale instead of using random huge values.
Knowledge Check

Does `z-index: 999999` guarantee an element appears above every element on the page?