← Lessons

quiz vs the machine

Gold1480

Frontend

Stacking Context and Z Index

Why a high z index sometimes still loses.

5 min read · core · beat Gold to climb

Layers on the screen

When boxes overlap, the browser must decide which appears in front. Z index orders elements along the depth axis, but it only works among siblings inside the same stacking context.

What creates a context

A stacking context is a self contained group whose children are stacked together, then the whole group is placed as one unit in its parent. Several things create one:

  • The root element.
  • An element with a z index and a position other than static.
  • Opacity below one, a transform, a filter, or will change.

The common surprise

A child with z index of a million can still sit behind another box if its parent forms a stacking context that sits lower. The child can never escape its parent context. To fix layering bugs, find which ancestor created the context, not just the elements you see.

Key idea

Z index only orders siblings within the same stacking context, so a child can never rise above an element outside its parent context no matter how high its value.

Check yourself

Answer to earn rating on the learn ladder.

1. Z index orders elements only within

2. Which can create a new stacking context?

3. Why might a very high z index still appear behind?