z-index

Determines which element sits on top when elements overlap.

Initial value
auto
Inherited
No
Animatable
yes, as an integer
Applies to
positioned elements, flex items, and grid items
JavaScript
element.style.zIndex = "10"
On this page

Example

#
CSS
.header {
  position: sticky;
  top: 0;
  z-index: 10;
}
Preview

Definition and usage

#

The z-index property sets the stacking order on the axis perpendicular to the screen. An element with a higher value covers elements with a lower one. It works on positioned elements as well as on children of flex and grid containers.

The key concept is the stacking context. Elements only compare their z-index within the same context. If a parent creates its own context (for example through z-index, an opacity below 1, or transform), its children can’t rise above elements outside it, even with a value of 9999.

Without a z-index set, elements overlap in the order they appear in the code: a later one covers an earlier one.

Syntax

#
Syntax
z-index: auto | <integer>;

Values

#
  • auto

    Element 2 has no stacking context of its own and lands below elements 1 and 3.
  • 3

    <number>

    The highest value in the group, so element 2 sits on top.
  • -1

    <negative number>

    A negative value tucks the element below the others, even below the parent’s background if it has no context of its own.

Values in practice

#

auto

Element 2 has no stacking context of its own and lands below elements 1 and 3.
.demo { z-index: auto; }

3

The highest value in the group, so element 2 sits on top.
.demo { z-index: 3; }

-1

A negative value tucks the element below the others, even below the parent’s background if it has no context of its own.
.demo { z-index: -1; }

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Instead of competing with values like 9999, settle on a scale, for example 10 for the header, 100 for the menu, and 1000 for modal windows.
  • When z-index "doesn’t work," look for an ancestor that creates a new stacking context through transform, opacity, or filter.

Related entries

#

Spotted a mistake or missing an example? Write to us.