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

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 โŸฉ โž– โŸฉ static โŸฉ auto โŸฉ โž•

  • 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: root โŸฉ static block โŸฉ float โŸฉ static inline โŸฉ positioned

  • 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