Stacking Context

  • 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-modenormal

  • 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

z-index isn't purely a way to change an element's order, it's also a way to form a group around that element's children. z-index won't work unless a group is formed. 📗 Josh ⟩ What the heck, z-index?

Order in a Stacking Context

All the elements within a stacking context are stacked in this order (from back to front):

stacking order: root ⟩ ➖ ⟩ staticauto ⟩ ➕

  • 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)

Within flex containers, when the order property alters rendering from the "order of appearance in the HTML" , it similarly affects the order for stacking context❗️

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):

stacking order: rootstatic blockfloatstatic inlinepositioned

  • 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