Understanding CSS Stacking Contexts

Learn what CSS stacking contexts are, which properties create them, and how they affect z-index behavior in your layouts.

Stacking Contexts

Detailed Explanation

What Is a Stacking Context?

A stacking context is a three-dimensional conceptualization of HTML elements along the z-axis (toward or away from the viewer). When an element forms a stacking context, it creates a self-contained layer where its children's z-index values are resolved independently from the rest of the page.

Properties That Create Stacking Contexts

Several CSS properties trigger a new stacking context:

/* Positioned element with z-index other than auto */
.ctx-1 {
  position: relative;
  z-index: 1;
}

/* Element with opacity less than 1 */
.ctx-2 {
  opacity: 0.99;
}

/* Element with transform */
.ctx-3 {
  transform: translateZ(0);
}

/* Element with filter */
.ctx-4 {
  filter: blur(0);
}

/* Element with will-change */
.ctx-5 {
  will-change: transform;
}

/* Flex/grid child with z-index */
.ctx-6 {
  z-index: 1; /* inside a flex or grid container */
}

Why Stacking Contexts Matter for z-index

The critical rule is: z-index values are only compared within the same stacking context. A child element with z-index: 999999 inside a stacking context with z-index: 1 will never appear above a sibling stacking context with z-index: 2. This is the root cause of most "z-index doesn't work" frustrations.

Identifying Stacking Contexts

Use your browser's DevTools to inspect the stacking context tree. In Chrome, the Layers panel shows 3D visualization of composited layers. Firefox's 3D View does something similar. Understanding this hierarchy is essential for debugging z-index issues.

Best Practice

Mark layers that create stacking contexts in your z-index system. This tool lets you toggle the "ctx" flag on each layer so you can reason about the actual stacking behavior before writing any CSS.

Use Case

When you are debugging why a modal or tooltip appears behind another element despite having a higher z-index value, understanding stacking contexts reveals that the element's parent may be trapping its z-index within a lower stacking context.

Try It — z-index Manager

Open full tool