Lesson 23 +10 XP

Z-index

Z-index: the stacking ladder

When elements overlap, z-index decides who draws on top. Higher = on top.

Only on positioned & flex/grid

z-index works on positioned elements (relative, absolute, fixed, sticky) and flex/grid items. Plain static elements ignore it.

.box {
  position: absolute;
  z-index: 2;   /* on top of lower ones */
}

Same behavior as 'stacking order'

Without z-index, order in the DOM matters: later elements draw on top. Setting an explicit z-index lets you override that.

Stacking context

Each element that creates a stacking context (transform, opacity < 1, position+z-index, etc.) forms its own "layer", its children can't jump above elements outside it.

Workflow

  • Give \z-index: 1 to layers you want above.
  • Menu/back-to-top: high numbers like 9999, common to keep them on top.
  • Avoid huge numbers chaos; use small, meaningful tiers (10, 100, 1000).

Negative z-index

-1 puts an element BEHIND its parent's background. Useful for decorative shapes.

TL;DR

  • z-index picks stacking order among overlapping boxes.
  • Works on positioned + flex/grid items.
  • Higher number => on top.
  • Later DOM => on top when z-index ties.
  • Creates stacking contexts that contain children.