CSS Stacking Context
A stacking context is an atomic boundary on the Z-axis. Descendants are painted relative to their parent context and can never interleave in front of an external element stacked above that parent.
Stacking Context Trap on z-index: 9999
Toggle opacity or transform on the parent container to observe child isolation.
Under the Hood
- During the Paint phase of the Browser Rendering Pipeline, the engine sorts boxes across 7 stacking levels (context background,
z-index < 0, in-flow blocks, floats, inline,z-index: 0,z-index > 0). - Many non-positioning properties create a stacking context:
opacity < 1,transform !== none,filter !== none,isolation: isolate,contain: layout|paint. - A child stacking context is painted as a single atomic unit inside its parent before subsequent sibling contexts are drawn.
/* Header sits at root stacking order z-index: 10 */
.site-header { position: sticky; z-index: 10; }
/* Parent opacity < 1 creates a stacking context at z-index: 1 */
.card-wrapper { position: relative; z-index: 1; opacity: 0.99; }
/* Trapped inside .card-wrapper: still paints BEHIND .site-header */
.card-tooltip { position: absolute; z-index: 999999; }Problem Genealogy
- 1998 (CSS 2.0):
z-indexonly applies to positioned elements (relative,absolute,fixed). - 2011 (CSS3 Transforms/Opacity): Effects requiring an offscreen buffer (
opacity < 1,transform) implicitly create a stacking context. - 2015+ (
isolation: isolate): Dedicated property added to create a stacking context without visual side effects or forced GPU promotion.
Production Pitfalls
- Modal stuck under a header: An intermediate ancestor receives
transform: translateY(0)for an animation, trapping the modal'sz-index: 9999under the sticky header. z-index: 999999escalation: Adding extra nines toz-indexis the CSS equivalent of shouting louder in a soundproof room, it never crosses a parent stacking context boundary.
- When not to use
z-index: Use the Native<dialog>Element or Popover API in the Browser Top Layer for modals and tooltips instead of managing globalz-indexscales.
Connections & Logical Next Steps
Top Layer elements paint in a dedicated layer above the entire document root stacking context.
Portals only exist to escape local ancestor stacking contexts and overflow clipping.
Hit-testing and pointer interception depend on stacking context paint order absent in JSDOM.
Stacking context order determines DisplayItem emission order during the Paint phase.
Stacking contexts trap z-index inside ancestors, whereas the Top Layer renders above every stacking context.
The Top Layer bypasses the entire stacking context hierarchy and overflow: hidden clipping.
Seen in Architecture Autopsies
Mechanical Comparisons
Stacking contexts trap z-index inside ancestors, whereas the Top Layer renders above every stacking context.
The Top Layer bypasses the entire stacking context hierarchy and overflow: hidden clipping.