DEV Community

loading...

Stacking Context (CSS layouts)

poulamic profile image Poulami Chakraborty ・2 min read

So far we have talked about positioning in the 2D plane. It is also possible to specify coordinates along a 3rd direction - the z-direction- which determines which box will be rendered on top in case of overlap.

And just like formatting context in the x-y plane, we have stacking context along the z-axis which determines the layout in the z-direction.

I mentioned that by default the layout is such that there is no overlap - in the x-y direction. There is, however, an overlap in the z-direction - children are stacked on top of parents

The deeper the element in the nesting, the higher up it appears.

Positioning & Floats impacts an elements position in the stacking context.

When the z-index property is not declared on any element, elements are stacked in the following order (from bottom to top):

  1. The background and borders of the element
  2. Descendant non-positioned blocks, in order of appearance in the HTML
  3. Descendant positioned elements, in order of appearance in the HTML

A positioned element with a z-index creates a new stacking context.

z-index

z-index is how we explicitly specify the stacking order of an element. This is another CSS property which seems so simple - elements with a higher z-index value are displayed in front of those with a lower z-index value. That's it.

Well, not actually. The main thing to understand is that z-index is not a global property - it is scoped within its own stacking context.

Every stacking context has a single HTML element as its root element. And the z-index of an element confined to a stacking context is set relative to that element.

Elements of 2 different stacking contexts cannot intermix. No matter how high the z-index an element cannot be placed on top of an element whose containing stacking order is higher.

That sounds too complex- we will consider with a different example.

Alt Text
For analogy, consider this organization of books in a shelf - we can re-organize the books in each drawer, but never can a book in the blue layer appear above books in the orange layer, or below books in the pink layer. We need to change the order of the drawers in order to do that.

Watch out for

  • Position: z-index only works on positioned elements (i.e. non-static elements)
  • Stacking context created: New stacking contexts are created by opacity, transforms, filters
  • Pseudo elements: Pseudo-elements are treated as descendants of their associated element. To position a pseudo-element below its parent, you have to create a new stacking context to change the default stacking order.

Discussion

pic
Editor guide