flashman
← All guides

CSS stacking contexts, z-index, and reliable overlay layers

Design reliable CSS overlay layers by understanding stacking contexts, paint order, clipping, portals, the browser top layer, accessibility, and responsive tests.

2026-09-01 · 8 min read

  • css
  • frontend
  • accessibility

z-index orders boxes inside a stacking context; it is not one global number line for the page. Once an ancestor establishes a context, its descendants are painted together relative to sibling contexts, regardless of how large a descendant z-index becomes.

Positioned elements with a non-auto z-index are only one source. Opacity below one, transforms, filters, isolation, several containment modes, and other rendering features can establish contexts. Overflow, clip-path, and masks can hide an overlay without changing stacking order.

Diagnose the context tree

Start at the obscured element and walk toward the root in browser developer tools. Record each context-creating declaration and clipping ancestor, then compare the nearest relevant ancestor with its siblings.

  • Inspect computed styles rather than only authored rules.
  • Temporarily outline ancestor boxes to expose clipping.
  • Distinguish DOM order, stacking order, and the browser top layer.
  • Reduce the case before deleting performance-related declarations.

Create a deliberate layer architecture

Define a short semantic scale for content, sticky navigation, menus, popovers, backdrops, and modals. Components should request a named layer rather than inventing increasingly large numbers.

Render app-wide overlays through a root portal when they must escape local contexts and clipping. Native dialog and popover features can use the browser top layer, but they still require support checks and correct interaction behavior.

Treat accessibility as part of the overlay

A visually corrected modal is still broken if keyboard focus remains behind it, screen readers can navigate obscured content, or scroll locking shifts the page. Keep focus restoration, escape behavior, backdrop semantics, and reduced-motion preferences in the component contract.

  • Verify text and backdrop contrast.
  • Test zoom, forced colors, and high-contrast themes.
  • Keep tooltip and menu content reachable by keyboard.
  • Avoid portals that disconnect labels or reading order.

Verify representative layouts

Use Flashman's CSS formatter to expose context declarations, color tool to test foreground and backdrop contrast, diff tool to review computed-style changes, HTML entities tool for reduced markup, and Markdown editor to document the project's layer scale.

Test transformed and scrolling containers, sticky headers, nested overlays, mobile viewports, native dialogs, focus traps, page zoom, reduced motion, forced colors, server rendering, and transitions that temporarily add transforms.

Try these tools