Understanding CSS z-index and Stacking Contexts
This article explains the default stacking order of HTML elements, how z-index interacts with positioned, floating, and flex items, how to create custom stacking orders, and the rules for generating stacking contexts, providing practical examples and best‑practice recommendations for front‑end developers.
The article, originally published in the 奇舞周刊 by front‑end engineer Gao Feng, introduces the concept of z-index and how it controls the stacking order of elements on the Z‑axis in CSS.
It starts with a simple example (demo1) showing two <div class="box box1">DIV#1,z-index为2</div> <div class="box box2">DIV#2,z-index为auto</div> where the element with a higher z-index does not appear on top because it is not positioned, illustrating that z-index only affects positioned elements.
The article then details the default stacking order when no z-index is used: root background and border, non‑positioned block elements in source order, and positioned block elements in source order. It notes that the order property of flex items also influences stacking.
Next, it explains how floating blocks fit into the stacking order—between non‑positioned and positioned elements—demonstrated with demo4 and demo5, and shows that inline content inside non‑positioned elements can appear above floating elements due to the standard wrapping behavior.
The author moves on to customizing stacking order with z-index , emphasizing three key points: the default value is auto , equal z-index values fall back to the default rules, and z-index only works on positioned elements. Several demos (demo6, demo8, demo9) illustrate how changing z-index on positioned elements creates a new stacking context that isolates child elements.
A major focus is the concept of stacking contexts . The article lists eleven conditions that generate a stacking context (e.g., positioned elements with a non‑auto z-index , elements with opacity less than 1, transformed elements, etc.) and explains how contexts nest, how their z-index values are only compared within the same parent context, and why z-index cannot cross parent boundaries.
Finally, the author provides practical advice: avoid overusing z-index , keep the stacking‑context hierarchy shallow and aligned with the HTML hierarchy, and plan z-index usage early to prevent unpredictable layout issues.
The article concludes with a summary and references for further reading on CSS stacking contexts and z-index.
360 Tech Engineering
Official tech channel of 360, building the most professional technology aggregation platform for the brand.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.