What Creates a New Stacking Context in CSS?

A stacking context is a three-dimensional conceptualization of HTML elements along the imaginary z-axis relative to the user. Understanding what triggers a new stacking context is essential for mastering CSS layering, as child elements within a stacking context cannot escape their parent’s stacking order, regardless of their own z-index values. This article covers the primary CSS properties and values that generate new stacking contexts, from classic positioning rules to modern CSS layout and compositing features.

The Root Stacking Context

The base stacking context is automatically established by the root element of the document, which is the <html> element in standard web pages. Every other element on the page exists within this initial context unless a distinct property creates a localized sub-context.

Position and z-index

The most traditional method for instantiating a new stacking context involves combining CSS positioning with the z-index property.

Flexbox and Grid Child Items

Direct children of flex containers (display: flex or display: inline-flex) and grid containers (display: grid or display: inline-grid) generate a stacking context when their z-index property is set to any value other than auto. Unlike standard block-level elements, flex and grid items do not require explicit position declarations to utilize z-index for stacking context creation.

Visual and Transform Properties

Several visual rendering and compositing properties force the browser to composite an element separately, resulting in the creation of a new stacking context:

Isolation and Containment

Modern CSS provides explicit mechanisms for isolating components and managing rendering boundaries:

Compositing and Performance Properties

Stacking Context Containment

Once a stacking context is formed, all descendant elements are grouped and rendered within that single layer relative to elements outside of it. A child element with z-index: 9999 inside a parent element with z-index: 1 will never appear in front of an external sibling element with z-index: 2. Managing these boundary conditions ensures predictable layer stacking and prevents common layout conflicts.