robohash image acting as kam's profile photo

Tip 007 - Stacking Contexts


Stacking contexts is a tricky concept and a not-very-fun-sounding one at that. The thing with stacking is that there's a few gotchas that can, well, getcha if you're not aware of them.

But first a recap: By default, on a web page, elements will flow, meaning one appears after another. Whether they appear below the last thing or next to it depends on the space in the viewport, the size of the elements, and what display mode they're using. (Block, inline, etc.)

By doing various things to an element in CSS, you can override that and make things appear on top of other things. When this happens there's a stacking context in play, and it decides in what order the things overlap each other, or in other words, which elements are on top. The elements competing for the top are in the same context. To decide with CSS what order these things are in, we have the z-index property. Higher numbers are closer to the top. By default, or in a tie, the last thing in the markup is on top.

Here are some things are can create new stacking contexts:

  • Setting position
  • Setting opacity
  • Setting transform, mask, filter, perspective, and other cool things
  • Setting z-index on a flex item or a grid item
  • Having an HTML document at all

These are all capable of starting their own stacking contexts. The key takeaway here is that when you have multiple contexts in play, an item in one context cannot compete with an item in another context. Each context has its own item order, and each context will compete with other contexts as items would.

In the example below, the HTML document is one context, and the 3 div elements that were absolutely positioned created another context. As a result the text is hidden behind the boxes, since their context was already higher.

See the Pen YzKrMOB by Kam Black (@kamblack) on CodePen.

For more info:


Have you written a reply on another site? Put the URL here: