Layout

z-index

z-index sets which overlapping elements are drawn in front (the stacking order) with an integer. Higher values come to the front.

Syntax

auto | <integer>

Preview

1234
Presets
Sample
Items
Drag the bottom-right corner to resize

Code

.box {
  display: flex;
}

.box > :nth-child(2) {
  z-index: 1;
}

Controls

z-index1
1234

About

Values

Write auto (the initial value) or an integer; negative values are allowed. Within the same stacking context (explained below), elements with higher values are drawn in front, and among equal values, the element later in the HTML comes to the front.

The preview on this page makes the box display: flex with a helper declaration and puts z-index on the second of the overlapping items only (.box > :nth-child(2) is a selector for the second child of the box). With auto, later items are in front, so item 3 hides the right edge of item 2. With 1, item 2 comes in front of both neighbors.

Where it applies

z-index works on elements whose position isn't static, and on flex and grid items. On ordinary block or inline elements it changes nothing until you set position.

Stacking contexts

An element with a value other than auto creates a stacking context. The z-index values of its children are compared only within that context. When a parent creates a context, no value on a child, however large, brings it in front of elements outside the parent.

Elements with opacity below 1, with transform or filter, or with isolation: isolate, among others, create stacking contexts too. When things don't stack the way you expect, check whether a parent has one of these.

0 versus auto

0 creates a stacking context and is drawn after items with auto. So with the 0 preset, item 2 comes in front of item 3, which stays auto.

Negative values go behind the box's background

An element with a negative value is drawn behind the backgrounds of ordinary elements in its nearest stacking context. The box in this preview doesn't create one, so with -1 item 2 goes behind the box's white background and disappears. Give the box isolation: isolate or the like to create a context, and the item is drawn in front of the box's background but behind the other items.

Comments