首先,要想使用z-index属性,则元素的position属性必须 不为static
我有两个div元素,.box元素具有transform属性,.son元素具有z-index:-1;属性
代码如下:
<style>
.box{
position: relative;
width: 200px;
height: 200px;
background-color: #f27979;
transform: translateX(100px);
}
.son{
position: absolute;
top:25%;
width: 300px;
height: 100px;
background-color: #35bcfa;
z-index: -1;
}
</style>
<div class="box">
box
<div class="son">son</div>
</div>
浏览器效果如下图
显然,.son元素的z-index失效了
但是如果我去掉.box元素的transform属性(看右边的.box样式表)
效果如下:
.son元素的z-index可以生效
伪元素与子元素同理。
我又创建了一个与.son同级的兄弟元素,对于兄弟元素,即使transform后,z-index也会生效,只有父子之间不生效
代码如下:
<style>
.box {
position: relative;
width: 200px;
height: 200px;
background-color: #f27979;
transform: translateX(100px);
/* z-index: 1; */
}
.son {
position: absolute;
top: 25%;
width: 300px;
height: 100px;
background-color: #35bcfa;
/* transform: translateX(100px); */
z-index: -2;
}
.brother {
position: absolute;
background-color: black;
width: 600px;
height: 100px;
z-index: -1;
}
</style>
<div class="box">
box
<div class="brother"></div>
<div class="son">son</div>
</div>
效果: