What is z-index?

z-index controls the stacking order of overlapping elements: higher values appear in front. It only applies to positioned elements (relative, absolute, fixed, sticky) and to flex or grid items, and it only competes within the same stacking context, which is why a z-index: 9999 sometimes still ends up behind something else.

Stacking contexts

A stacking context is an isolated layer; its children are stacked inside it and cannot escape above elements outside it. New stacking contexts are created by:

  • a positioned element with a z-index other than auto,
  • opacity below 1, transform, filter, perspective, clip-path, mask,
  • isolation: isolate, will-change on those properties, contain: paint,
  • position: fixed and sticky,
  • flex/grid children with a z-index.

Classic bug

A modal with z-index: 1000 inside a header that has transform (or z-index: 1) can never appear above the page content that has z-index: 2, because the whole header context sits at layer 1.

Best practices

  • Use a small, documented scale (e.g. --z-dropdown: 10; --z-sticky: 20; --z-modal: 100; --z-toast: 200) instead of random large numbers.
  • Use isolation: isolate on components to contain their internal z-indexes.
  • Render modals and popovers in the top layer (<dialog>.showModal() or the popover attribute), which sits above everything regardless of z-index, or portal them to <body>.

Interview tip

Explaining stacking contexts is the real answer here; "use a bigger number" is the wrong one.

Code example

html
1<style>
2 body { font-family: system-ui; }
3 .box { position: absolute; width: 140px; height: 70px; padding: 6px; border: 2px solid #0b1020; color: white; }
4 .stage { position: relative; height: 170px; }
5 .a { background: #2b4bff; top: 0; left: 0; z-index: 1; }
6 .b { background: #e11d48; top: 30px; left: 60px; z-index: 2; }
7 /* Parent creates a stacking context at level 1 ... */
8 .parent { position: absolute; top: 80px; left: 0; z-index: 1; }
9 /* ... so z-index 999 inside it still loses to .c (z-index 2) */
10 .child { background: #059669; top: 0; left: 120px; z-index: 999; }
11 .c { background: #0b1020; top: 95px; left: 180px; z-index: 2; }
12</style>
13<div class="stage">
14 <div class="box a">z 1</div>
15 <div class="box b">z 2 (in front)</div>
16 <div class="parent"><div class="box child">z 999 trapped in parent z 1</div></div>
17 <div class="box c">z 2 wins</div>
18</div>
19<button onclick="document.querySelector('dialog').showModal()">Open top-layer dialog</button>
20<dialog><p>Top layer beats every z-index.</p><form method="dialog"><button>Close</button></form></dialog>

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.

Open in study app