CSS Stacking Context

CSS Stacking Context

When you first start out in CSS the stacking context is not something you come across too often, a few z-index rules will normally sort you out. However, it has bitten me in the bum a few times so thought I would share some insight into it.

What is the CSS Stacking Content

A stacking context is a group of layers in the DOM, that are stacked in a specific order.  in its most basic form, this is the root HTML element on the page. However, this is the part that is often overlooked and can be the source much pain in debugging layering issues in CSS. The stacking context can be formed, anywhere in the document, by any element in the following scenarios:
  • The root element of the document (usually the HTML tag).
  • An element with a position value “fixed” or “sticky”
  • Element with a position value “absolute” or “relative” and z-index value other than “auto”.
  • The element that is a child of a flexbox container, with a z-index value other than one set to “auto”.
  • An element with an opacity value less than 1.
  • An element with a mix-blend-mode value other than “normal”.
  • Element with a -webkit-overflow-scrolling value “touch”.
  • Any element with the following properties with a value other than “none”:
    • transform
    • filter
    • perspective
    • clip-path
    • mask / mask-image / mask-border
Within a stacking context, child elements are stacked according to the same rules previously explained. And much more importantly the most overlooked feature, the z-index values of its child stacking contexts only have meaning in this parent. So it might seem like a complex set of rules but if you think about it as simple groups of layers that have their own order you should be able to work out where you are going wrong and with the above rules you can easily work out where these stacking contexts are formed.

Useful Tools for debugging the Stacking Content

If you do get a bit stuck along the way there are a few helpful tools that can help if you get stuck with the stacking context.

Chrome Layers

This is built into the browser and can be accessed by opening the developer tools, from the dot menu clicking ‘more tools’ and then ‘layers’ You will then get a view of the dom that you can rotate and view the layers that build up your website or web app.

Z-context – the z-index plugin

Z-context is a plugin for chrome that displays stacking contexts and z-index values in the elements panel when you select an element in the dom. Whats great about this plugin is it will tell you what caused the stacking context to be created.