Search code examples
htmlcsscss-positionz-indexabsolute

Element with z index -1 goes under grandparent's div


Putting z-index:-1 into absolute-child make the div under the grandparent. How do I make absolute-child go under the parent div not the grandparent div?

.grandparent{
  background:rgba(0, 128, 0, 0.89);
  width:500px;
}

.parent{
  position:relative;
  width:200px;
  height:200px;
  background:yellow;
}

.absolute-child{
  position:absolute;
  width:100px;
  height:100px;
  background:red;
  top:10px;
  right:-50px;
  z-index:-1;
}
 <div class="grandparent">
    <div class="parent">
      <div class="absolute-child"> absolute ch
      </div>
      <div class="siblings">siblings</div>
    </div>
 </div


Solution

  • Here is what you want, added position: relative; to the granparent so the z-index: 0; work for it.

    .grandparent{
      background:rgba(0, 128, 0, 0.89);
      width:500px;
          z-index: 0;
        position: relative;
    }
    
    .parent{
      position:relative;
      width:200px;
      height:200px;
      background:yellow;
    }
    
    .absolute-child{
        position: absolute;
        width: 100px;
        height: 100px;
        background: red;
        top: 10px;
        right: -50px;
        z-index: -1;
    }
    <div class="grandparent">
        <div class="parent">
          <div class="absolute-child"> absolute ch
          </div>
          <div class="siblings">siblings</div>
        </div>
     </div