CSS negative z-index: what does it mean?

The accepted answer is on the right track, but isn’t entirely true.

For starters, the initial value of z-index is auto, not 0.

When you assign an element z-index: 0 (or any other integer), you’re creating a new stacking context. z-index: auto does not create a stacking context. This is important because a parent with auto will appear in front of a child with -1, but a parent with 0 will appear behind a child with -1 (see snippet).

Each stacking context will order its content according to the stacking order.

It’s also important to note that z-index only works on positioned elements. Positioned elements are anything other than the initial position: static – so relative, absolute, etc.

Additionally, you should be aware that changes to certain css properties like filter, transform and opacity can also create a new stacking context. See the resources below for more clarity.

p {
  position: absolute;
  top: 100%;
  width: 200px;
  margin: 0
}
.container {
  width: 200px;
  height: 200px;
  display: inline-block;
  background: none;
}
.box {
  position: relative;
  background: lightgrey;
  width: 100px;
  height: 100px;
  padding: 15px;
}
.red {
  background: lightcoral;
}
.z-1 {
  z-index: -1;
}
.z0 {
  z-index: 0;
}
<div class="container">
  <div class="box">
    z auto (initial)
    <div class="box red z-1">z -1</div>
  </div>
  <p>Parent: auto / Child: -1</p>
</div>
  
<div class="container">
  <div class="box z0">
    z 0
    <div class="box red z-1">z -1</div>
  </div>
  <p>Parent: 0 / Child: -1</p>
</div>

Additional Information

CSS properties that create a stacking context

See how opacity can affect the stacking context

Read another in-depth article on stacking order.

stacking order

Leave a Comment