Z-Index & Stacking Context
The z-index property and stacking context rules that govern front-to-back painting order when UI layers overlap
Table of Contents
Structure Diagram
What is Z-Index & Stacking Context?
The z-index property and stacking context rules that govern front-to-back painting order when UI layers overlap. It is a core concept in Layout & Responsive within UI / UX.
Core Principles
While z-index controls front-to-back painting order, its values are only compared within the same Stacking Context. A new stacking context is created not just by positioned elements with a z-index, but also by properties like opacity < 1, transform, filter, backdrop-filter, and isolation: isolate.
Because stacking contexts are strictly hierarchical, a child with z-index: 99999 inside a lower-ranked parent can never paint above a sibling stacking context that sits higher in the tree.
Practical Takeaways
- Define a semantic z-index scale: Prevent
9999escalation wars by centralizing tokens such assticky (10),dropdown (20),overlay (30),modal (40), andtoast (50). - Scope internal layers with
isolation: isolate: Wrapping a component root withisolation: isolatecreates a clean local stacking context without relying on dummyz-index: 0hacks. - Escape trapped contexts via Portals or Top Layer: Render modals, popovers, and tooltips into a root portal or use native
<dialog>/ Popover API so ancestoroverflowortransformrules never clip them.
Notable Examples
- Design system layer tokens: Standardized elevation tiers shared across header, drawer, modal, and toast primitives.
- Native
<dialog>top layer: Browser-managed top-layer rendering that sits above every CSSz-indexautomatically. - Hover transform bug fix: Resolving a dropdown hidden behind an adjacent card whose hover
transformunexpectedly spawned a new stacking context.