Posted over 4 years ago. Visible to the public. Repeats.

z-index: About stacking contexts

The CSS property z-index is not as global as you might believe. Actually, it is scoped to a so-called "stacking context". z-indexes only have meaning within their stacking context, while stacking contexts are treated as a single unit in their parent stacking context. This means indices like 99999 should never actually be needed.

Creating a new stacking context

In order to create a stacking context with the least possible side effects, use these properties on an element:

position: relative // or absolute z-index: 0 // or any other number

Note that many more properties create a new stacking context, like position:fixed, position:sticky, opacity, transform. See the attached link for a full list.

Using negative z-indexes

A negative z-index pushes an element down the stack. To profit from this, make sure a parent element creates a new stacking context. Then, within this context, you can move elements to the back (e.g. background images, gradients etc). They will be rendered behind all other elements within the context (e.g. text), but not behind elements outside the stacking context (like the page background).

Stacking context illustration

Study this example graphic for a quick understanding of how stacking contexts work:

Further reading

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Dominik Schöler
Last edit:
18 days ago
by Dominik Schöler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Dominik Schöler to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more