问题
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.
回答1:
An element with a negative z-index will be rendered under most elements, unless they have an even lower z-index.
回答2:
The accepted answer is on the right track, but isn't entirely true.
For starters, the default 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 default position: static
- so relative
, absolute
, etc.
z-index
can be a little less straightforward than most of us think. See the additional information below for more clarity.
div {
position: relative;
top: 0;
left: 0;
width: 100px;
height: 100px;
background: lightgrey;
padding: 15px;
}
p {
position: absolute;
top: 100%;
width: 200px;
margin: 0
}
.wrapper {
width: 100%;
background: none;
}
.container {
width: 200px;
height: 200px;
display: inline-block;
background: none;
}
.box {
position: relative;
float: left;
top: auto;
left: auto;
}
.red {
background: lightcoral;
}
.z-auto {
z-index: auto;
}
.z-1 {
z-index: -1;
}
.z0 {
z-index: 0;
}
.z1 {
z-index: 1;
}
<div class="wrapper">
<div class="container">
<div class="box">
z auto (default)
<div class="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="red z-1">z -1</div>
</div>
<p>Parent: 0 / Child: -1</p>
</div>
</div>
Additional Information
See how opacity can affect the stacking context
Read another in-depth article on stacking order.
来源:https://stackoverflow.com/questions/33217407/css-negative-z-index-what-does-it-mean