Search code examples
htmlcssz-indexpseudo-element

z-index isn't working with relative parent & after/before elements


I have such code (prototype):

.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

why my red block isn't under the text?


Solution

  • Add z-index: -1 on the before element.

    .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>