In Positioning we learned how to move boxes around, and we saw that positioned boxes can overlap: a badge hangs over a card, a dropdown covers the content below it, a modal covers the whole page. When two boxes overlap, the browser must decide which one is drawn in front. The property you reach for is z-index.
Almost every developer has had this experience: you set z-index: 9999 on a dropdown, and it still appears behind some other element. That isn't a browser bug. It happens because of stacking contexts. Once you understand them, z-index stops feeling like magic. That is the goal of this chapter.
The Third Dimension
A web page has an x-axis (left to right) and a y-axis (top to bottom). The z-axis points out of the screen, towards the person looking at it. Boxes with a higher position on the z-axis are closer to the viewer and cover boxes behind them.
viewer 👀
▲ z-axis
│
┌───────────┴──┐ z-index: 3 (front)
│ ┌───────────┴──┐ z-index: 2
│ │ ┌───────────┴──┐ z-index: 1 (back)
└──│ │ │
└──│ │
└──────────────┘
z-indexsets the stack level of a box along the z-axis inside its stacking context. Boxes with a higher stack level are painted in front of boxes with a lower one. The values are integers (they can be negative) orauto, which is the default.
Default Order: Without Any z-index
Even with no z-index anywhere, overlapping boxes still follow rules. Two simple ones cover most cases:
Positioned elements are painted on top of non-positioned ones. A box with
position: relative(or absolute, fixed, sticky) covers ordinary static boxes that it overlaps.Among similar elements, later in the HTML is painted on top. If two absolute boxes overlap, the one that comes later in the source wins.
<div class="box a">A</div>
<div class="box b">B</div>.box {
position: absolute;
width: 120px;
height: 80px;
}
.a { top: 20px; left: 20px; background: tomato; }
.b { top: 50px; left: 70px; background: steelblue; }B overlaps A and is drawn on top, simply because it comes later in the HTML. Add z-index: 1 to .a and now A comes to the front.
Rule 1: z-index Needs a Positioned Element (or a Flex/Grid Item)
z-index only has an effect on:
positioned elements (
positionisrelative,absolute,fixedorsticky), andflex items and grid items — even if they are
static.
.card {
z-index: 10; /* does NOTHING: .card is static and not a flex/grid item */
}
.card {
position: relative;
z-index: 10; /* works */
}The flex-item exception surprises many people. In our Chrome test, two static flex items were made to overlap with a negative margin; the first one had z-index: 2 and no position at all, and it was drawn on top of the second one. (Flexbox itself is the topic of Flexbox.)
Rule 2: z-index Values Compare Only Inside the Same Stacking Context
This is the rule that explains every "my z-index doesn't work" bug.
A stacking context is a group of elements that are stacked together as one unit. The element that creates it is its root. Children inside a stacking context are ordered among themselves, and then the whole group is placed in the parent stacking context as a single layer, using the root's own z-index.
Think of it like folders and pages. Each stacking context is a folder. You can reorder the pages inside a folder however you like (that's z-index of the children), but a page can never escape its folder. If folder 1 is under folder 2 on the desk, every page in folder 1 is under every page in folder 2 — even a page marked "z-index 9999".
Another way: think of version numbers. A child's z-index is like the minor number. 1.9999 is still smaller than 2.0, because the major number (the parent context's z-index) is compared first.
Worked example: the modal that hides behind the header
<div class="header">Header</div>
<div class="main">
<div class="modal">Modal</div>
</div>.header {
position: relative;
z-index: 2;
height: 60px;
background: navy;
color: white;
}
.main {
position: relative;
z-index: 1; /* creates a stacking context! */
}
.modal {
position: absolute;
top: -40px; /* moved up so it overlaps the header */
left: 100px;
z-index: 9999;
width: 200px;
height: 80px;
background: crimson;
color: white;
}Result in Chrome: the red modal's top part is hidden behind the navy header. The word "Modal" is not even visible, because it sits in the covered area.
Let's trace why, step by step:
Root stacking context (html)
├── .header z-index: 2 ← compared here
└── .main z-index: 1 ← compared here
└── .modal z-index: 9999 ← only compared to other children of .main
1. .main has position: relative + z-index: 1 → it creates a stacking context.
2. .modal's 9999 is only meaningful INSIDE .main.
3. At the root level, the browser compares .header (2) with .main (1).
4. 2 > 1, so .header and everything in it is in front of .main
and everything in it — including the modal.Fixes (any one works):
Remove
z-index: 1from.main(so it no longer creates a stacking context and the modal competes at the root level).Give
.maina z-index higher than the header's.Move the modal's HTML out of
.main, directly into<body>. This is why UI libraries render modals and tooltips in a "portal" at the end of the body.Use the HTML
<dialog>element opened withshowModal()(or thepopoverattribute). These are placed in the browser's top layer, which sits above every stacking context on the page.
What Creates a Stacking Context?
This list is a favourite interview question, and the surprising entries cause most real bugs. An element creates a new stacking context if it is:
| Condition | Example |
|---|---|
| The root element | <html> |
position: relative or absolute with a z-index other than auto | position: relative; z-index: 0; |
position: fixed or sticky (always, even with no z-index) | position: sticky; top: 0; |
A flex item or grid item with a z-index other than auto | z-index: 1 on a child of display: flex |
opacity less than 1 | opacity: 0.99; |
transform, scale, rotate, translate, filter, backdrop-filter, perspective, clip-path, mask / mask-image / mask-border not none | transform: translateX(0); |
mix-blend-mode other than normal | mix-blend-mode: multiply; |
isolation: isolate | Created specifically for this purpose |
will-change naming any of the properties above | will-change: transform; |
contain with layout or paint (also strict, content) | contain: paint; |
container-type: size or inline-size | Container query containers (see Container Queries) |
Elements in the top layer (and their ::backdrop) | Modal <dialog>, popovers, fullscreen elements |
Notice how many of these have nothing to do with z-index. A harmless-looking opacity: 0.95 fade or a transform hover effect on a parent can trap a child's dropdown inside a new stacking context.
Important:
position: relativewithout a z-index (i.e.z-index: auto) does not create a stacking context.z-index: 0does. That difference is small to type and big in effect.
The Painting Order Inside a Stacking Context
Within one stacking context, the browser paints layers in this order, from back to front:
Back
1. Background and borders of the element that forms the stacking context
2. Positioned descendants with NEGATIVE z-index (most negative first)
3. Normal in-flow block boxes (non-positioned)
4. Floats (non-positioned)
5. Inline content: text, images, inline boxes (non-positioned)
6. Positioned descendants with z-index: auto or 0 (in HTML order)
7. Positioned descendants with POSITIVE z-index (lowest first)
FrontThis order explains several behaviours:
A positioned box with no z-index (layer 6) covers static boxes (layers 3–5). That's the "positioned wins" rule from earlier.
Floats (layer 4) are painted above the backgrounds of normal blocks (layer 3) but below inline content such as text (layer 5). So a float that overlaps a following block covers that block's background, while the block's text is never hidden under the float (you will see how text wraps around floats in Float & Clear).
A negative z-index element goes behind normal content, but never behind the background of its stacking context root (layer 1).
Worked example: negative z-index and the parent
<div class="parent">
Parent
<div class="child">Child z-index: -1</div>
</div>.parent {
position: relative; /* z-index: auto → NOT a stacking context */
width: 200px;
height: 60px;
background: gold;
}
.child {
position: absolute;
z-index: -1;
top: 20px;
left: 40px;
width: 200px;
height: 60px;
background: purple;
color: white;
}Result: the purple child is drawn behind the gold parent. The parent is not a stacking context, so the child's -1 is compared in an outer context, where it goes below the parent's in-flow box.
Now add z-index: 0 to .parent. The parent becomes a stacking context, so its own background is layer 1 of that context, and the child (layer 2) is painted above the gold background. We verified both cases in Chrome: without z-index: 0 the child's text was hidden behind the gold box; with it, the purple box and its text appeared in front.
This trick is commonly used for decorative layers: a ::before pseudo-element with z-index: -1 placed behind a button's text, but still above the button's own background.
isolation: isolate — Creating a Context on Purpose
Sometimes you want a component to form its own stacking context, so its inner z-index values (or negative z-index decorations) can never leak out and fight with the rest of the page. The cleanest tool is:
.card {
isolation: isolate;
}It creates a stacking context and does nothing else — no visual change, no positioning, unlike opacity or transform. It is supported in all modern browsers.
Managing z-index in a Real Project
Random values like z-index: 99999 scattered through a codebase lead to "z-index wars". A better habit is a small, documented scale that the whole team follows:
/* z-index scale for this project:
dropdown 100 · sticky 200 · overlay 300 · modal 400 · toast 500 */
.site-header { position: sticky; top: 0; z-index: 200; }
.dropdown-menu { position: absolute; z-index: 100; }
.modal { position: fixed; inset: 0; z-index: 400; }Later, in CSS Variables (Custom Properties), you will see how to store such a scale in named variables so the numbers live in one place.
Combined with isolation: isolate on components, most z-index values can stay small (1, 2, 3) because they only compete within their own component.
Debugging checklist
Is the element positioned (or a flex/grid item)? If not, z-index is ignored.
Walk up its ancestors. Does any of them create a stacking context (z-index set, opacity, transform, filter, will-change, sticky/fixed…)?
If yes, compare that ancestor against the element you're fighting, not the element itself.
Browser DevTools can help: Chrome and Edge have a Layers panel, and Firefox shows a note in the Inspector when z-index has no effect.
Common Mistakes
Setting z-index on a static element (that is not a flex/grid item) and expecting it to work.
Increasing the number instead of finding the stacking context. 9999 cannot beat a sibling of your ancestor with a higher z-index.
Forgetting that opacity, transform, filter and will-change create stacking contexts. Adding a hover animation to a parent can suddenly break a dropdown.
Thinking z-index: 0 and z-index: auto are the same. Both paint in the same layer, but
0creates a stacking context andautodoes not.Using a negative z-index and losing the element behind an ancestor's background. Give the intended parent a stacking context (
isolation: isolateorz-index: 0) so the element stays above that parent's background.
Interview / Exam Questions
1. What is a stacking context?
A stacking context is a group of elements that are painted together as one layer. Its children are ordered by z-index among themselves, and the whole group is then placed in its parent stacking context according to the root element's own z-index. A child can never be painted above or below something outside its stacking context independently of its root.
2. Why can an element with z-index: 9999 appear behind an element with z-index: 2?
Because they are in different stacking contexts. If an ancestor of the 9999 element creates a stacking context with z-index 1, and the other element (or its context) has z-index 2 in the same parent context, the browser compares 1 vs 2. Everything inside the z-index: 1 context, including the 9999 element, goes behind.
3. Name five properties that create a new stacking context.
Any five of: position relative/absolute with z-index not auto; position: fixed or sticky; opacity below 1; transform (or scale/rotate/translate) not none; filter or backdrop-filter not none; isolation: isolate; mix-blend-mode not normal; will-change naming such a property; contain: paint/layout; a flex or grid item with z-index not auto; container-type: size/inline-size.
4. Does z-index work on an element with position: static?
Normally no. The exception is flex items and grid items: their z-index works even when they are static.
5. Two absolutely positioned siblings overlap and neither has a z-index. Which is on top?
The one that comes later in the HTML source. Positioned elements with z-index auto (or 0) in the same stacking context are painted in document order.
6. A child with z-index: -1 disappears behind its parent's background. How do you fix it while keeping it behind the parent's content?
Make the parent a stacking context, for example with isolation: isolate or position: relative; z-index: 0. The root's background is always painted first in its own stacking context, so the negative child is then drawn above the parent's background but below its normal content.
Summary
z-indexcontrols front-to-back order, but only for positioned elements and flex/grid items.Without z-index, positioned elements are painted over non-positioned ones, and later elements over earlier ones.
z-index values are only compared inside the same stacking context. A stacking context is painted as one unit in its parent.
Stacking contexts are created by z-index on positioned elements, fixed/sticky, opacity < 1, transforms, filters,
isolation: isolate,will-change,containand more.The painting order inside a context is: root background → negative z → blocks → floats → inline content → z auto/0 → positive z.
Use a small z-index scale and
isolation: isolateinstead of ever-growing numbers.
Next we look at an older layout tool that also takes boxes out of the normal flow, but in a very different way: Float & Clear.