What does z-index do?
Web pages are flat, but elements can overlap: dropdown menus over content, popups over the whole page, sticky headers over text as you scroll. The CSS z-index property decides which overlapping element appears in front. Think of it as the distance from the screen: a higher number is closer to you. This interactive tester lets you change the numbers and immediately see the result.
How to use the tester
- Change the z-index of boxes A, B and C. The highest number moves to the front.
- Untick
position: relativeto see that z-index is ignored on unpositioned elements. - Tick the stacking context option and give Box C a very high value such as 999. It still cannot rise above a box with z-index 1, and the explanation tells you why.
The three rules to remember
- z-index only works on positioned elements (relative, absolute, fixed or sticky) and on flex or grid children. On a normal static element it does nothing.
- Equal values are ordered by the HTML. If two elements have the same z-index, the one that appears later in the code is on top.
- Stacking contexts are sealed boxes. When a parent creates a stacking context, its children are layered only inside it. A child with z-index 9999 can never appear above an element that sits higher than its parent.
What creates a stacking context?
A new stacking context is created by an element with a position and a z-index other than auto, and also by opacity below 1, transform, filter, position: fixed or sticky, and isolation: isolate. This is why adding a transform to a parent can suddenly break a dropdown menu.
Frequently asked questions
Why is my z-index: 9999 not working?
Either the element is not positioned, or one of its parents has created a stacking context with a lower value. Inspect the parents for transform, opacity or z-index.
Can z-index be negative?
Yes. A negative value places an element behind its parent's content, which is useful for decorative backgrounds.
Is there a maximum z-index?
Browsers accept up to 2,147,483,647, but a simple scale such as 10, 20, 30 is far easier to maintain.