What @BoltClock said is right.
Not specifying z-index
is the same as z-index: auto;
that is its initial value.
About z-index: 0
it's important to note the following:
z-index: 0
creates a stacking context while z-index: auto
do not. You can check MDN for more information about this.
In most cases this won't affect the rendered elements.
The following is an example where it matters:
.box {
position: relative;
width: 64px;
height: 64px;
top: 32px;
left: 32px;
}
.red {
background: red;
}
.green {
background: green;
}
.blue {
background: blue;
}
#example-auto {
display: inline-block;
}
#example-0 {
display: inline-block;
margin-left: 64px;
}
<div id="example-auto">
<div class="box red">
<div class="box green" style="z-index: 1"></div>
</div>
<div class="box blue"></div>
</div>
<div id="example-0">
<div class="box red" style="z-index: 0">
<div class="box green" style="z-index: 1"></div>
</div>
<div class="box blue"></div>
</div>
In both cases, red and blue are siblings with a position: relative
and green is a child of red with position: relative
and z-index: 1
:
- Root
- Red:
position: relative
- Green:
position: relative; z-index: 1
- Blue:
position: relative
In the first example, green will be positioned above red and blue. This is because it has a z-index: 1
, so a stacking context is created and put above the root context.
In the second example, green will be positioned above red, but below blue. This is because red has z-index: 0
, so it creates a stacking context at the same level of blue. So green will be above red (because green also creates a stacking context), but below blue because it's trapped in the context of red.
Here's a more practical example. We want an object
element wrapped in an a
element. When the data is an svg, the anchor will be ignored when hovering over the svg. To fix this, we can use z-index: 0
for a
and z-index: -1
for object
.
<a href="#test1" style="display: inline-block; width: 100px">
<object type="image/svg+xml" data="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/star.svg"></object>
</a>
<a href="#test2" style="display: inline-block; width: 100px; position: relative; z-index: 0">
<object type="image/svg+xml" data="https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/star.svg" style="position: relative; z-index: -1"></object>
</a>