父级的background-color
和border-radius
隐藏在伪元素的后面。即使伪元素的z-index
为-1,为什么伪元素也不位于父元素的后面?
.btn {
text-decoration: none;
background-color: royalblue;
font-family: sans-serif;
font-weight: bold;
border-radius: 5px;
color: white;
display: inline-block;
padding: 20px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.btn::after {
content: "";
display: inline-block;
width: 100%;
height: 100%;
background-color: cornflowerblue;
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
<a href="#" class="btn">Download free app</a>
答案 0 :(得分:0)
您只需要将overflow: hidden;
添加到父元素。
.btn {
text-decoration: none;
background-color: royalblue;
font-family: sans-serif;
font-weight: bold;
border-radius: 5px;
color: white;
display: inline-block;
padding: 20px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
overflow: hidden;
}
.btn::after {
content: "";
display: inline-block;
width: 100%;
height: 100%;
background-color: cornflowerblue;
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
<a href="#" class="btn">Download free app</a>
答案 1 :(得分:0)
罪魁祸首是创建堆叠上下文的transform
属性,因此您的伪元素将被绘制在该堆叠上下文中,并且在逻辑上将位于背景之上,而您将使用z-index
。
删除变换以查看区别。我增加了border-radius
并更改了颜色以更好看。
.btn {
text-decoration: none;
background-color: red;
font-family: sans-serif;
font-weight: bold;
border-radius: 50px;
color: white;
display: inline-block;
padding: 20px;
position: absolute;
top: 50%;
left: 50%;
}
.btn::after {
content: "";
display: inline-block;
width: 100%;
height: 100%;
background-color: cornflowerblue;
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
<a href="#" class="btn">Download free app</a>
如果您希望伪元素位于父元素之下,则应避免创建堆栈上下文的任何属性,否则将是不可能的。
或者您可以考虑使用另一个伪元素来创建背景图层,并且可以根据需要控制堆栈:
.btn {
text-decoration: none;
font-family: sans-serif;
font-weight: bold;
color: white;
padding: 20px;
position: absolute;
transform:translate(-50%,-50%);
top: 50%;
left: 50%;
}
.btn::before,
.btn::after{
content: "";
position: absolute;
top: 0;
left: 0;
right:0;
bottom:0;
z-index:-1;
}
.btn::before {
background-color: cornflowerblue;
}
.btn::after {
background-color: red;
border-radius: 50px;
}
<a href="#" class="btn">Download free app</a>
一些相关问题:
Why elements with z-index can never cover its child?
Is there any way to place z-index according not to its parent element