Sub topic 10
Stacking contexts and why z-index sometimes fails
This chapter assumes you know the position values and the z-index basics from the previous chapter. You should be comfortable reading the browser's developer tools and the DOM tree.
A common bug looks like this. You give a dropdown z-index: 9999 and it still renders behind another element. The cause is almost never the number. It is the stacking context the element lives in.
What a stacking context is
A stacking context is a group of elements that the browser paints together as one unit. Inside the group, elements are ordered by their z-index values. From outside, the whole group counts as a single layer with the z-index of the element that created it.
Two rules follow from this:
- An element's
z-indexis compared only with its siblings in the same stacking context. - A child can never be painted between two elements that sit outside its context. It stays inside the layer its ancestor created.
The page itself is the first stacking context. The <html> element creates it and it is called the root stacking context. Every other context is nested inside it, so the page forms a tree of contexts.
A failing z-index, step by step
Here, the tooltip has z-index: 9999 and the box B has z-index: 2. The tooltip still ends up behind B.
<div class="a">
A (z-index: 1)
<div class="tip">Tooltip (z-index: 9999)</div>
</div>
<div class="b">B (z-index: 2)</div>
<style>
.a, .b {
position: relative;
width: 200px;
height: 100px;
}
.a {
z-index: 1;
background: #fcd;
}
.b {
z-index: 2;
background: #cdf;
margin-top: -40px;
}
.tip {
position: absolute;
top: 60px;
left: 20px;
z-index: 9999;
background: #333;
color: #fff;
padding: 4px;
}
</style>Box A has position: relative and a z-index other than auto, so it creates a stacking context. The tooltip belongs to that context. The browser first orders A and B in the root context: B (2) is above A (1). A is painted as one flat layer, tooltip included, so the whole layer lands below B. The 9999 is only compared with other children of A.
The next diagram shows the tree of contexts.
The fix is to change the comparison that matters, which is A against B. Giving A a z-index of 3 puts the whole group, tooltip included, above B.
.a {
z-index: 3;
}What creates a stacking context
Many developers expect only z-index to do this. In practice, several unrelated properties create a context too. The table lists the common triggers.
| Trigger | Creates a context when |
|---|---|
| Root element | Always (`<html>`) |
| `position: relative` or `absolute` | `z-index` is not `auto` |
| `position: fixed` or `sticky` | Always, even with `z-index: auto` |
| Flex or grid item | `z-index` is not `auto`, even without `position` |
| `opacity` | Value is less than 1 |
| `transform`, `filter`, `perspective`, `clip-path` | Value is not `none` |
| `mask` and related properties | Value is not `none` |
| `isolation` | Value is `isolate` |
| `mix-blend-mode` | Value is not `normal` |
| `will-change` | It names a property that would create a context, such as `transform` or `opacity` |
| `contain` | Value includes `layout` or `paint` |
The unexpected entries are opacity, transform and filter. A harmless fade or hover animation on a wrapper can quietly trap every descendant's z-index.
.card {
opacity: 0.99;
}
.card .menu {
position: absolute;
z-index: 500;
}Here .card becomes a stacking context because its opacity is below 1. The menu's 500 now only competes with other things inside the card. If a later sibling of the card is positioned, it can cover the menu.
Paint order inside one context
When two elements are in the same context, the browser paints them in a fixed order, from back to front:
- The background and borders of the element that created the context.
- Descendants with a negative
z-index, most negative first. - In-flow, non-positioned block elements, in tree order.
- Floating elements.
- In-flow inline content, such as text.
- Positioned descendants with
z-index: autoor0, in tree order. - Descendants with a positive
z-index, lowest first.
Elements with the same value are painted in source order, so the later one sits on top. Steps 2, 6 and 7 are the reason a positioned element appears over plain content even without any z-index. A child that creates its own context is painted at its z-index position in this list, as one unit.
A negative z-index places an element behind its parent's non-positioned content, but still in front of the parent's own background, if the parent is a stacking context. If the parent is not a context, a negative child can drop behind the parent's background and even behind an ancestor's background. This is a common surprise.
<div class="outer">
<div class="behind">Behind text</div>
Parent text
</div>
<style>
.outer {
position: relative;
z-index: 0;
background: #eee;
padding: 2rem;
}
.behind {
position: absolute;
top: 0;
left: 0;
z-index: -1;
background: gold;
}
</style>The z-index: 0 on .outer makes it a context. The gold box sits behind the text but stays visible over the grey background. Remove the z-index: 0 and the gold box can go behind the grey background in a context higher up, so it may disappear.
Using isolation on purpose
You can use the same behavior to protect a component. If a widget uses z-index internally for its own layers, those numbers can leak into the page and fight with other components. Creating a context at the widget's root keeps them contained.
.widget {
isolation: isolate;
}isolation: isolate creates a stacking context and has no other visual effect. That makes it a clean way to scope internal z-index values. Unlike position: relative; z-index: 0, it needs no positioning, so it does not change layout or make the element a containing block for absolutely positioned children.
Fixing a trapped element
You have three real options when an element is trapped in a lower context:
- Raise the
z-indexof the ancestor that creates the context, as in the A and B example. This is the smallest change, but it can affect other overlaps involving that ancestor. - Remove the property that creates the context, if it is not needed. An
opacity: 0.99left from an old experiment is a typical candidate. - Move the element in the DOM so it is a child of a higher-level container, such as a direct child of
<body>. Modals, tooltips and dropdown menus are often handled this way. Component libraries call it a portal.
The third option is the most dependable for overlays. It also avoids a second problem: transform, filter and perspective on an ancestor change the containing block of position: fixed descendants. A fixed modal inside a transformed wrapper is then positioned against the wrapper, not the viewport.
Debugging checklist
- Confirm that both elements can use
z-index. Check that each is positioned, or is a flex or grid item. - Find the nearest ancestor of each element that creates a stacking context. In browser developer tools, look for computed values of
opacity,transform,filter,isolation,will-changeandposition. - Find the lowest common ancestor context of the two elements.
- Compare the
z-indexvalues of the two children of that context that contain your elements. These are the numbers that decide the result. - Apply one fix and test it. If the order does not change, return to step 2. A second context may exist higher in the tree.
Exercises
Exercise
A page has .sidebar { position: relative; z-index: 1; } and .content { position: relative; z-index: 2; }. A dropdown inside .sidebar has z-index: 99999 and overlaps .content. It appears behind .content. Why, and what is a minimal fix?
Show answer
.sidebar creates a stacking context because it is positioned with a z-index other than auto. The dropdown's 99999 is compared only inside the sidebar. In the root context, .sidebar (1) is below .content (2), so the entire sidebar, dropdown included, is painted below .content. A minimal fix is to give .sidebar a z-index higher than .content, for example 3. Moving the dropdown out of the sidebar in the DOM also works.
Exercise
A card has transition: opacity 0.2s and a hover rule sets opacity: 0.99. Absolutely positioned menus inside the card with z-index: 10 are covered by a later sibling card only while the hover is active. What explains this, and how can you avoid it?
Show answer
While the card has opacity below 1, it creates a stacking context, and the menu's z-index is trapped inside it. The card is then painted as one layer at its own position in the parent context, where a later positioned sibling can cover it. When the opacity returns to 1, the context disappears and the menu is compared with the sibling directly. To avoid it, give the card a stable context, for example position: relative; z-index: 1, and raise the hovered card above its siblings, or avoid animating opacity on the card.
Exercise
What is the difference between isolation: isolate and position: relative; z-index: 0 as ways to create a stacking context?
Show answer
Both create a stacking context. isolation: isolate does nothing else, so the element stays in normal flow without being positioned. position: relative; z-index: 0 also makes the element positioned, which makes it the containing block for absolutely positioned descendants and can change how they are placed.