Stacking context

On this page 7

A stacking context in CSS is a three-dimensional grouping of elements along the imaginary z-axis, inside which descendants are painted in a defined order and compared with each other only. The group as a whole is then placed into its parent stacking context as a single unit, so no descendant can rise above or sink below content outside the group, whatever its z-index value.

Understanding stacking contexts explains most of the puzzling layering bugs in front-end work, such as a dropdown that stays hidden behind a header despite z-index: 9999. The root element always forms the first stacking context, and many other properties create new ones, often as an unintended side effect.

How a stacking context orders painting

Inside each stacking context, the browser paints content in a fixed sequence of layers defined by the CSS 2.1 specification, Appendix E, and refined by later modules. Elements later in this sequence appear in front of earlier ones, and elements within the same layer are painted in document source order.

The following table lists that painting order from back to front.

OrderLayerWhat it contains
1Root backgroundBackground and borders of the element forming the context
2Negative z-indexPositioned descendants with z-index below zero, lowest first
3Block-level flowNon-positioned block descendants in source order
4FloatsNon-positioned floating descendants
5Inline contentInline and inline-block descendants, including text
6Z-index zero or autoPositioned descendants with z-index 0 or auto, in source order
7Positive z-indexPositioned descendants with z-index above zero, lowest first
Painting order inside one stacking context

The crucial rule is atomicity: once an element forms a stacking context, its entire subtree is resolved first and then treated as one painted layer at the position of that element in its parent context. A child with z-index: 1000 inside a parent with z-index: 1 is still behind a sibling of the parent that has z-index: 2.

Properties that create a stacking context

A new stacking context is created by a long list of property values, not only by z-index. Many of them are visual or performance properties whose layering effect is easy to overlook, which is why stacking bugs often appear after an unrelated change such as adding a fade animation.

The table below groups the most common triggers and their typical origin in real code.

TriggerConditionTypical origin
Positioned with z-indexposition relative or absolute and z-index not autoDeliberate layering
Fixed or sticky positionposition fixed or sticky, alwaysHeaders and toolbars
Flex or grid child with z-indexz-index not auto on a flex or grid itemCard layouts
Opacity below 1Any value under 1Fade effects and disabled states
Transform, filter, perspectiveAny value other than noneAnimations and hover effects
Mix-blend-modeAny value other than normalDecorative blending
Isolation isolateisolation set to isolateExplicit grouping without side effects
Will-changeNaming a property that creates a contextPerformance hints
Containlayout, paint, strict or contentRendering optimization
Top layerModal dialogs, popovers, fullscreenNative overlays
Common triggers of a new stacking context

Because a stacking context is also a natural compositing boundary, browsers often promote such elements to separate GPU layers. Creating many of them, for example through blanket will-change rules, can raise memory use without any visible benefit.

A stacking context is frequently confused with neighboring ideas in CSS layout and rendering. Distinguishing them helps locate the real cause of a layering problem instead of escalating z-index values.

ConceptWhat it controlsRelationship to stacking context
Z-indexOrder of an element within its current contextMeaningful only inside a stacking context
Containing blockReference box for sizing and positioningIndependent; a transform affects both
Block formatting contextFloat containment and margin collapsingSeparate mechanism with different triggers
Cascade layersPriority of style rulesUnrelated despite the similar word
Top layerRendering above the whole documentEscapes all page stacking contexts
Related layering concepts

The top layer deserves special attention: content placed there through showModal(), the popover API or the Fullscreen API is rendered above every stacking context in the document, which makes it the reliable modern solution for overlays that must never be clipped or covered.

Debugging and controlling stacking contexts

Effective debugging starts by finding the nearest ancestor that forms a context for each element involved, then comparing those ancestors rather than the elements themselves. Browser developer tools help: Chromium offers a Layers panel and a 3D view, and Firefox marks elements that create a stacking context in its layout inspection.

  • Walk up the DOM tree and note every ancestor with a context-creating property.
  • Compare elements at the level where their ancestor chains diverge.
  • Adjust z-index on those sibling ancestors, not on the deeply nested child.
  • Use isolation: isolate to create a context without visual side effects.
  • Move overlays to the top layer or render them near the end of the body.

A disciplined team also defines a small z-index scale, for example five named levels stored in CSS variables, instead of arbitrary values. Combined with deliberate isolation of components, this keeps layering predictable as the code base grows.

Common mistakes with stacking contexts

Most failures follow a few recognizable patterns. The table below links each symptom to its usual cause and a durable fix.

SymptomLikely causeDurable fix
Dropdown hidden behind a headerDropdown parent forms a lower contextRaise the parent or move the menu to the top layer
Overlay jumps behind content during animationTransform or opacity creates a context mid-transitionSet the context permanently with isolation
Negative z-index child disappearsChild slides behind an ancestor backgroundGive the intended parent its own context
Z-index has no effectElement is static and not a flex or grid itemAdd position relative or adjust layout
Ever-growing z-index valuesTeams compete without a shared scaleIntroduce named layering tokens
Typical layering bugs

The deepest misconception is that z-index is a global ranking across the page. It is a local ranking within one context, and recognizing that distinction resolves most layering disputes.

Put simply

Think of a web page as a stack of transparent sheets. A stacking context is like stapling several sheets into one booklet. Inside the booklet, the sheets can be rearranged freely. The whole booklet, however, moves as one piece within the larger pile.

So a sheet inside one booklet can never slip between the sheets of another booklet. That is why a menu with a huge layer number can still hide behind a header. The real fix is to move the whole booklet, not to shout a bigger number.

In practice

A front-end developer at an online retailer receives a report that the account menu opens behind the sticky promotion banner. The menu already has z-index: 999, while the banner has only z-index: 10. Inspection shows that the menu sits inside the site header, which uses transform: translateZ(0) added years earlier as a performance hint, so the header forms its own context with an implicit z-index of zero.

Raising the menu value changes nothing, because it competes only inside the header. The developer removes the obsolete transform, gives the header position: sticky with z-index: 30 from the shared layering scale, and sets the banner to the lower token of 20. The menu now appears above the banner on every page, and the fix requires two declarations instead of escalating numbers.