element::后z-index不工作



嘿,我对这段代码有一个问题:

#selector{
width:100%;
height:100px;
background-color:#333;
position: fixed;
transform: translate(50%);
right: 50%;
top: 10px;
width: 95%;
z-index: 20;
}
#selector::after{
content: '';
width: 95%;
height: 10px;
position: absolute;
right: 50%;
bottom: -4px;
border-radius: 5px;
transform: translate(50%);
background: #3D74FE;
z-index: -1;
}
<div id="selector"></div>

你可以看到我有一个z-index#selector::在之后,但它不起作用,它没有在#selector后面!!!

子z-index对父z-index不起作用

解决方案:

#selector{
width:100%;
height:100px;
transform: translate(50%);
right: 50%;
top: 10px;
width: 95%;
position: relative;
}
#selector::before{
content: '';
width:100%;
height:100%;
background-color:#333;
position: absolute;
right: 0;
top: 0;
}
#selector::after{
content: '';
width: 95%;
height: 10px;
position: absolute;
right: 50%;
bottom: -4px;
border-radius: 5px;
transform: translate(50%);
background: #3D74FE;
z-index: -1;
}

z-index将不工作,如果你有transform属性*。

position属性不是static,relative,absolute*。

*见参考。

您可以从父元素中删除z-index(它应该在蓝线之上)。(参考).

所以,新的CSS是:

#selector{
width:100%;
height:100px;
background-color:#333;
position: relative;
/*transform: translate(50%);*/
/*right: 50%;
top: 10px;*//* use margin */
width: 95%;
/*z-index: 20;*/
margin: 0 auto;
}
#selector::after{
content: '';
width: 95%;
height: 10px;
position: absolute;
right: 50%;
bottom: -4px;
border-radius: 5px;
transform: translate(50%);
background: #3D74FE;
z-index: -1;
}
<div id="selector"></div>

在jsfiddle上看

最新更新