Tech Interview RoomStudy guides

HTML & CSS

Explain CSS positioning and stacking contexts. Why does z-index sometimes not work?

Intermediate · 2 min read · Lesson 5 of 7 in HTML & CSS

position

  • static (default): normal flow; top/left and z-index do nothing.
  • relative: stays in flow, offset visually; becomes the anchor for absolute children.
  • absolute: removed from flow, placed relative to the nearest positioned ancestor.
  • fixed: relative to the viewport (unless an ancestor has a transform, filter or perspective, which becomes the containing block).
  • sticky: acts relative until a scroll threshold, then sticks inside its scroll container. It fails if an ancestor has overflow: hidden or the parent is no taller than the element.

Stacking contexts

z-index only compares elements inside the same stacking context. A new context is created by: a positioned element with a z-index other than auto, opacity below 1, transform, filter, isolation: isolate, flex or grid children with z-index, position: fixed/sticky, will-change and a few more.

So a modal with z-index: 9999 inside a parent with transform or z-index: 1 can still sit below a sibling with z-index: 2: the whole parent is ranked as one unit.

Fixes

Render modals, tooltips and toasts into a top-level container (React portals with createPortal, Vue <Teleport to="body">), or use the native <dialog> with showModal() or the Popover API, which use the browser's top layer above everything.

Example

css
.header { position: sticky; top: 0; z-index: 10; }

.tooltip-anchor { position: relative; }
.tooltip { position: absolute; bottom: 100%; left: 50%; transform: translateX(-50%); }

.widget { isolation: isolate; }   /* contain this component's z-index values */
html
<button popovertarget="menu">Menu</button>
<div id="menu" popover>Rendered in the top layer, no z-index needed</div>

Follow-up questions interviewers ask

Try answering each one before you open it.

What is CSS anchor positioning?

A newer feature (anchor-name, position-anchor, position-area, position-try-fallbacks) that lets a tooltip or popover be positioned relative to another element in pure CSS, including flipping when it would overflow the viewport. It removes the need for JavaScript positioning libraries where browsers support it; check support and keep a fallback.