Search code examples
htmlcssz-index

z-index is not working with pseudo elements


I want to add after pseudo element for div. I did this in react. When I test it in codepen, it works in codepen. But in my local machine, it is not working. I applied z-index pseudo element only in codepen, But it works. In my project, Even I applied z-index for both parent div and pseudo element, it does not help. What mistake I did? Anyone, Please guide me. Thanks in Advance. My code is: HTML:

        <div className='cards'>
          <div className='card active'>Card</div>
          <div className='card'>Card</div>
          <div className='card'>Card</div>
        </div>

CSS:

.card {
  width: 300px;
  height: 200px;
  background-color: #fff;
  border-radius: 5px;
  &.active {
    position: relative;
    box-shadow: 10px 10px 60px rgba(0, 0, 0, 0.1);
    z-index: 10;
    &::after {
      position: absolute;
      content: "";
      top: 0;
      left: 0;
      width: calc(100% + 5px);
      height: calc(100% + 15px);
      border-radius: 5px;
      background-color: #923929;
      z-index: -1000;
      transform: rotateZ(-2deg);
      transform-origin: top left;
    }
  }
}
.cards {
  padding: 5rem;
  display: flex;
  gap: 20rem;
  background-color: #92392920;
}

output is output

without z-index for parent div output looks like this. parent without z-index


Solution

  • If you add z-index to parent you create new stacking context

    Just remove z-index from parent element

    UPD

    Yes. also I need to add the background for section element

    .what_we_do{
      background-color: #fff6f6;
      padding:5rem;
    }
    .card {
      width: 300px;
      height: 200px;
      background-color: #fff;
      border-radius: 5px
    }
    
    .card.active {
      position: relative;
      box-shadow: 10px 10px 60px rgba(0, 0, 0, 0.1);
    }
    
    .card.active::after {
      position: absolute;
      content: "";
      top: 0;
      left: 0;
      width: calc(100% + 5px);
      height: calc(100% + 15px);
      border-radius: 5px;
      background-color: #923929;
      z-index: -1;
      transform: rotateZ(-2deg);
      transform-origin: top left;
    }
    
    .cards {
      padding: 5rem;
      display: flex;
      gap: 20rem;
      background-color: #92392920;;
      position: relative;
      z-index: 1;
    }
    <section class="what_we_do">
    <div class="cards">
    
      <div class="card active">Card</div>
      <div class="card">Card</div>
      <div class="card">Card</div>
    </div>
    </section>

    UPD: from comment

    I want to add effects for active card i.e. brown background for active card.

    .card.active{
      background-color:#923929;
    }