HTML & CSS Course
HTML & CSS
/
Advanced

z-index & Stacking Context

Definition

The `z-index` property specifies the stack order of an element. An element with greater stack order is always in front of an element with a lower stack order.

Explain Like I'm New

If the X-axis is Left/Right, and the Y-axis is Up/Down, the Z-axis is towards the user's face. If two boxes overlap, the browser needs to know which one goes on top. The one with the higher `z-index` number wins.

Real World Example

A dropdown menu. If you click a dropdown, it must have a high `z-index` so it overlaps the text and images below it, instead of sliding underneath them.

Common Use Cases

  • •Modals
  • •Dropdowns
  • •Sticky Headers

Interactive Example

Interview Questions

basic

  • Can you apply a `z-index` to a `position: static` element?

intermediate

  • You have a Modal with `z-index: 9999`, but a button with `z-index: 1` is somehow rendering ON TOP of it. Why?

Flash Cards

Question

Apply to static?

Click to reveal answer
Answer

No. `z-index` ONLY works on positioned elements (`relative`, `absolute`, `fixed`, or `sticky`).

Question

Z-index 1 beating 9999?

Click to reveal answer
Answer

This is a 'Stacking Context' issue. Z-indexes only compete against siblings in the same parent. If your Modal is inside a parent div that has a `z-index: 0`, the Modal's 9999 is trapped inside that parent. The button (which might be outside that parent) easily overlaps the parent, trapping the modal underneath.