负z索引在伪元素之后不起作用

时间:2017-05-25 08:01:51

标签: html css sass frontend pseudo-element

我不明白为什么当我把z-index作为负值而其他div没有z-index值时,伪元素:: after不会落在蓝框后面。截至目前,蓝色方框位于黄色方框后面,但我希望黄色方框位于蓝色方框下方,但红色方框位于红色方框之上。

.menu1{
  height: 100px;
  width: 100px;
  background-color: red;
}
.menu1 .menupicture1{
  width: 50px;
  height: 50px;
  position: relative;
  top: 90px;
  background-color: blue;
}

.menu1 .menupicture1::after{
  content: "";
  display: block;
  height: 75px;
  width: 75px;
  background-color: yellow;
  z-index: -1;
}
<div class="menu1">
        <div class="menupicture1"></div>
</div>

3 个答案:

答案 0 :(得分:1)

您缺少伪元素中的position:absolute

更新下面的css部分:

.menu1 .menupicture1::after{
  content: "";
  display: block;
  height: 75px;
  width: 75px;
  background-color: yellow;
  z-index: -1;
  position:absolute; /* add this property */
}

.menu1{
  height: 100px;
  width: 100px;
  background-color: red;
}
.menu1 .menupicture1{
  width: 50px;
  height: 50px;
  position: relative;
  top: 90px;
  background-color: blue;
}

.menu1 .menupicture1::after{
  content: "";
  display: block;
  height: 75px;
  width: 75px;
  background-color: yellow;
  z-index: -1;
  position:absolute;
}
<div class="menu1">
        <div class="menupicture1"></div>
</div>

答案 1 :(得分:1)

您需要为元素position

more info

.menu1 {
  height: 100px;
  width: 100px;
  background-color: red;
  z-index: 1;
  position: relative;
}

.menu1 .menupicture1 {
  width: 50px;
  height: 50px;
  position: relative;
  top: 90px;
  background-color: blue;
}

.menu1 .menupicture1::after {
  content: "";
  display: block;
  height: 75px;
  width: 75px;
  background-color: yellow;
  z-index: -1;
  position: relative;
}
<div class="menu1">
  <div class="menupicture1"></div>
</div>

答案 2 :(得分:1)

红色框和黄色框中使用否定z-index,并向其添加position:relative;

&#13;
&#13;
.menu1{
  height: 100px;
  width: 100px;
  background-color: red;
  position:relative;
  z-index: -1;
  
}
.menu1 .menupicture1{
  width: 50px;
  height: 50px;
  position: relative;
  top: 90px;
  background-color: blue;

}

.menu1 .menupicture1::after{
  content: "";
  display: block;
  height: 75px;
  width: 75px;
  background-color: yellow;
  position:relative;
  z-index: -1;

}
&#13;
<div class="menu1">
        <div class="menupicture1"></div>
</div>
&#13;
&#13;
&#13;