Sobes.tech
Middle

Why does z-index not work as expected — an element with a smaller z-index overlaps an element with a larger z-index?

sobes.tech AI

Answer from AI

The reason why an element with a lower z-index can overlay an element with a higher z-index is usually related to stacking contexts in CSS.

Key points:

  • z-index only works within a single stacking context.
  • A new stacking context is created, for example, when positioning (position other than static) and setting z-index, as well as with some other properties (e.g., opacity less than 1, transform, filter, etc.).
  • If two elements are in different stacking contexts, their z-index values cannot be directly compared — the order of contexts in the DOM tree is important.

Example:

.parent1 {
  position: relative;
  z-index: 1; /* creates a stacking context */
}
.child1 {
  position: absolute;
  z-index: 10; /* inside parent1 */
}
.parent2 {
  position: relative;
  z-index: 2; /* another stacking context, above parent1 */
}
.child2 {
  position: absolute;
  z-index: 1; /* inside parent2 */
}

In this case, .child2 will overlay .child1, despite having a lower z-index, because .parent2 has a higher z-index and is higher in the stack.

Conclusion: For z-index to work as expected, you need to consider stacking contexts and the DOM structure, not just the numerical z-index values of individual elements.