CSS Reference ยท Positioning and Stacking
The z-index property
Reference for the CSS z-index property: how stacking order works, which elements it applies to, how stacking contexts trap values, and common mistakes.
The z-index property controls the stacking order of overlapping elements along the z-axis, the line pointing out of the screen toward you. An element with a higher value is painted in front of one with a lower value, provided both belong to the same stacking context.
It works on positioned elements (anything except position: static) and on flex and grid items. A non-auto z-index on such an element also creates a new stacking context, which is where most z-index confusion comes from.
.modal { position: fixed; z-index: 100; }
Try it
In the second example the child's huge number cannot lift it above the teal box. Its parent forms a stacking context at level 1, so the child is stacked inside the parent, and the whole parent still sits below the box with level 2.
Syntax
z-index: auto | <integer>;
- Initial value:
auto - Applies to: positioned elements, and flex and grid items
- Inherited: no
- Animatable: yes, as an integer
- Computed value: as specified
Values
| Value | Description |
|---|---|
auto |
The element is stacked at level 0 in its parent's context and does not create a new stacking context (unless something else forces one). |
<integer> |
The stack level within the current context. Negative values are allowed and paint behind the context's normal content. The element also creates a new stacking context. |
Usage notes
- Positioned or flex/grid only. On a plain
staticblock,z-indexis ignored. Addposition: relativeif you need stacking without moving anything. - Only compare siblings in one context. Numbers in different stacking contexts are never compared. Debug by finding the nearest ancestor that creates a context.
- Other things create contexts too:
opacitybelow 1,transform,filter,isolation: isolate,position: fixedorsticky,will-changefor such properties, andcontain: paint. - Avoid arms races.
z-index: 99999is a symptom. Define a small scale (for example 10, 20, 30) in custom properties and useisolation: isolateon components to keep their internals contained. - Equal values stack in source order: later elements paint in front.
- Top layer. Modal dialogs and popovers render in the browser's top layer above all
z-indexvalues.
Browser support
Supported in every browser. The flex and grid item behavior is supported in all modern browsers.
Related
isolationโ create a stacking context on purposepositionopacity,transform- Lesson: CSS z-index