为什么伪元素背景隐藏父母?

问题描述 投票:0回答:2

父母的background-colorborder-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>
html css background z-index pseudo-element
2个回答
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


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>
© www.soinside.com 2019 - 2024. All rights reserved.