Skip to the page

The cascade and the box · mid

Positioning, z-index and stacking contexts

position decides what top/left are relative to (relative: itself, absolute: the nearest positioned ancestor, fixed: the viewport, sticky: its scroll container until it sticks), and z-index only compares elements inside the same stacking context.

The notes

What you must know

  • absolute is relative to the nearest ancestor with position other than static; otherwise the initial containing block.
  • sticky needs a threshold (top: 0) and stops at its parent's edge; overflow: hidden on an ancestor breaks it.
  • New stacking contexts: z-index on positioned elements, opacity < 1, transform, filter, isolation: isolate, position: fixed/sticky.
  • A child can't escape its parent's stacking context: z-index: 9999 inside a parent with z-index: 1 stays under a sibling with z-index: 2. A transformed ancestor also traps position: fixed.

The red pen

Common traps: mistake → fix

  • Mistake: "a bigger z-index always wins"

    Fix: only inside the same stacking context.

  • Mistake: "fixed is always relative to the viewport"

    Fix: a transformed ancestor becomes its containing block.

Easy to hard

Questions interviewers ask, easy to hard

  1. Explain the position values.
  2. Why does my modal with z-index 9999 appear under the header?
  3. Why is position: sticky not sticking?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview