CSS negative z-index: what does it mean?

Herbertusz picture Herbertusz · Oct 19, 2015 · Viewed 20.1k times · Source

What is the expected effect according to the standards, if I add a negative integer value to the z-index property of an element?

I searched for the answer but only have found this:
https://developer.mozilla.org/en-US/docs/Web/CSS/z-index
The "Negative values to lower the priority" doesn't mean anything for me.

Answer

sallf picture sallf · Jan 17, 2020

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