Stacking Context
- Josh ⟩ What the heck, z-index?? ⭐️⭐️⭐️ 
- HTMLElement ⟩ offsetParent - closest positioned ancestor element 
- Microsoft Edge ⟩ “3D view” - to view stacking contexts. 
- VSCode extension ⟩ CSS Stacking Contexts - highlight stacking contexts. 
- Chrome extension ⟩ - z-context - add a “z-index” pane to devtools. 
- CSS Stacking Context inspector - add a "stacking contexts" panel to DevTools. ⭐️ 
 
- Not all stacking contexts use positioned layout. 👉 See: Create Stacking Contexts 
- Not all positioned elements create a stacking context. (例如:只有 display: relative 沒有 z-index) 
Creating Stacking Contexts
- :root (<html>) - top-level stacking context 
- child inside a display: flex | grid , with z-index ≠ auto ( ⭐️ even static children ❗️ ) 
- position: relative | absolute, with z-index ≠ auto 
- position: fixed | sticky ( ⭐️ no z-index needed ❗️) 
- opacity < 1 
- mix-blend-mode ≠ normal 
- transform | filter | clip-path | perspective | mask (value ≠ none) 
- will-change: opacity | transform 
- contain: layout | paint 
- isolation: isolate - explicitly creates a context 
👉 See: 📘 MDN ⟩ The stacking context
Order in a Stacking Context
All the elements within a stacking context are stacked in this order (from back to front):
- the root element of the stacking context 
- positioned elements with a negative z-index (along with their children) 
- non-positioned (static) elements 
- positioned elements with a z-index of auto (and their children) 
- positioned elements with a positive z-index (and their children) 
Examples
Stacking without z-index
When the z-index property is not specified on any element, elements are stacked in the following order (from bottom to top):
- root element's background and borders 
- Descendant static blocks (in order of appearance in the HTML) 
- floating blocks 
- Descendant static inline elements 
- Descendant positioned elements (in order of appearance in the HTML) 
Last updated
Was this helpful?

