← Lessons

quiz vs the machine

Gold1380

Frontend

The Z Index And Stacking Context

See why a high z index sometimes fails and how stacking contexts box in your layering.

5 min read · core · beat Gold to climb

Layering along the z axis

The z index property controls paint order for positioned boxes along the depth axis. A larger value paints in front of a smaller one, but only when the boxes share the same stacking context. This is why a z index of nine thousand can still sit behind a sibling with a much smaller value.

  • z index only applies to positioned or flex and grid items.
  • Within one context, larger values paint on top.
  • The value is meaningless across different contexts.

What creates a context

A stacking context is a self contained layering group. Once an ancestor forms one, its descendants can never escape it to compare against outside boxes.

  • The root element forms the base context.
  • A positioned element with a z index forms one.
  • Opacity below one, a transform, a filter, or will change forms one.

When stacking goes wrong, the fix is usually finding the ancestor that created an unexpected context, not raising numbers higher.

Key idea

z index orders boxes only inside a shared stacking context, and properties like opacity and transform silently create new contexts that trap their descendants.

Check yourself

Answer to earn rating on the learn ladder.

1. Why might an element with a very high z index still appear behind another box?

2. Which property creates a new stacking context even without z index?