伪元素问题的z-index

时间:2017-07-11 20:34:45

标签: html css

我遇到一个问题,让我的伪元素落后于其父元素。我需要红色的盒子放在蓝色的盒子前面。

#mobile-nav-icon {
  position: absolute;
  display: block;
  height: 92px;
  width: 93px;
  background-color: red;
  right: 16px;
  top: 46px;
  z-index: 2;
}

#mobile-nav-icon:before {
  content: '';
  top: -9px;
  left: -10px;
  background-color: blue;
  height: 93px;
  width: 97px;
  position: absolute;
  z-index: -1;
}
<div id="mobile-nav-icon">
  <p>menu</p>
</div>

结果很奇怪,文本在伪元素前面,但父元素的背景不在。

有什么想法吗?

jsfiddle

2 个答案:

答案 0 :(得分:2)

删除第一条规则的z-index

#mobile-nav-icon {
  position: absolute;
  display: block;
  height: 92px;
  width: 93px;
  background-color: red;
  right: 16px;
  top: 46px;
}

#mobile-nav-icon:before {
  content: '';
  top: -9px;
  left: -10px;
  background-color: blue;
  height: 93px;
  width: 97px;
  position: absolute;
  z-index: -1;
}
<div id="mobile-nav-icon">
  <p>menu</p>
</div>

答案 1 :(得分:1)

尝试同时使用:before:after

&#13;
&#13;
#mobile-nav-icon {
  position: absolute;
}
#mobile-nav-icon:after {
  position: absolute;
  content: '';
  display: block;
  height: 92px;
  width: 93px;
  background-color: red;
  right: 16px;
  top: 46px;
  z-index: 2;
}

#mobile-nav-icon:before {
  content: '';
  position: absolute;
  z-index: 1;
  top: -9px;
  left: -10px;
  background-color: blue;
  height: 93px;
  width: 97px;
}
&#13;
<div id="mobile-nav-icon">
  <p>menu</p>
</div>
&#13;
&#13;
&#13;