Codectionary / Developer documentation / CSS

z-index and Stacking Context

z-index controls which element appears on top when elements overlap, but only works on positioned elements (anything other than static). Stacking contexts group elements together for z-index comparison purposes - z-index values only compete within the same stacking context, which is why a very high z-index can sometimes mysteriously fail to appear on top.

Syntax

z-index: number;

Examples

z-index Requires Positioning

A common mistake - z-index silently does nothing without position set.

.behind {
  z-index: 999; /* has NO effect - position is still static (the default) */
}

.in-front {
  position: relative; /* now z-index actually applies */
  z-index: 999;
}

The Stacking Context Trap

Why a huge z-index sometimes still loses to a smaller one.

.parent-a {
  position: relative;
  z-index: 1; /* creates a new stacking context */
}
.parent-a .child {
  position: relative;
  z-index: 9999; /* only competes WITHIN parent-a's stacking context */
}

.parent-b {
  position: relative;
  z-index: 2; /* parent-b beats parent-a entirely, so ALL its children render above,
                 regardless of how high a z-index .child has inside parent-a */
}

Parameters and values

  • z-index (number | auto): Stacking order among elements in the same stacking context

Best practices

  • Remember z-index only has an effect on positioned elements (position other than static) - set position: relative (or another value) first
  • Understand that properties like opacity < 1, transform, and filter also create new stacking contexts, which can trap z-index values unexpectedly
  • Use a documented, limited scale of z-index values across a project (like 10, 20, 30, 100 for modals) rather than arbitrary huge numbers, to keep stacking predictable
  • When a high z-index "does not work," the real cause is almost always an unexpected stacking context on an ancestor, not the z-index value itself being too low

At a glance

Purpose
Presentation and layout
File extension
.css
Runs in
Web browsers
Usually used with
HTML and JavaScript

Specifications & further reading

Related CSS documentation