z-index不适用于相对父级&元素之前/之后

时间:2018-06-13 12:50:37

标签: html css z-index pseudo-element

我有这样的代码(原型):

.headerz {
  position: relative;
  padding: 5rem 0 0 5rem;
  margin: 3rem 0 0 0;
  color: #000;
  font-size: 3.8rem;
  text-transform: uppercase;
  z-index: 24;
}

.headerz::before {
  content: "";
  position: absolute;
  width: 110px;
  height: 100px;
  left: 0;
  bottom: -3rem;
  background-color: red;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
  z-index: 22;
}

.headerz::after {
  content: "";
  position: absolute;
  width: 72px;
  height: 66px;
  left: 8.5rem;
  top: -2.8rem;
  background-color: blue;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
  z-index: 22;
}
<h3 class="headerz">Contacts</h3>

https://codepen.io/anon/pen/LrLjqQ

为什么我的红色块不在文本下?

1 个答案:

答案 0 :(得分:2)

在before元素上添加z-index: -1

.footer-contacts-header-main {
position: relative;
padding: 5rem 0 0 5rem;
margin: 3rem 0 0 0;
color: #000;
font-size: 3.8rem;
text-transform: uppercase;
z-index: 24;
}

.footer-contacts-header-main::before {
content: "";
position: absolute;
width: 110px;
height: 100px;
left: 0;
bottom: -3rem;
background-color: red;
background-size: contain;
background-repeat: no-repeat;
background-position: center center;
z-index: -1;
}

.footer-contacts-header-main::after {
content: "";
position: absolute;
width: 72px;
height: 66px;
left: 8.5rem;
top: -2.8rem;
background-color: blue;
background-size: contain;
background-repeat: no-repeat;
background-position: center center;
z-index: 22;
}
<h3 class="footer-contacts-header-main">Contacts</h3>