Search code examples
htmlcsspositionz-index

Embedded absolute div and z-index


I try to implement a dropdown-menu, that can be re-used in different divs.

I use position:relative for the dropdown menu(so it will appear under the button that is opening it). The problem is, that the dropdown menu is only overlaying it's parent divs: if the dropdown menu overlaps to an another (not parent) div, no matter the z-index I set, it underlays.

Is there a solution to make the absolute positioned item to be over everything else?

(I must use the z-indexes for other reasons, and I cannot make the menu display:relative)

.back, .front, .back2{
  position: absolute;
  width: 100px;
  color: white;
  line-height: 100px;
  text-align: center;
}

.back {
  position:relative;
  z-index: 10;
  top: 20px;
  left: 20px;
  background: red;
}
.back2 {
  position:relative;
  z-index: 10;
  top: 50px;
  left: 20px;
  background: orange;
}

.front {
  position: absolute;
  z-index:20;
  top: 60px;
  left: 60px;
  background: green;
}
<div class="back">
  <span >Parent div1</span>
  <div class="front">
    <span >dropdown</span>
  </div>
</div>

<div class="back2">
  <span >someOtherDiv</span>
</div>


Solution

  • There is no need to give z-index in parent div. Check updated snippet below

    .back, .front, .back2{
      position: absolute;
      width: 100px;
      color: white;
      line-height: 100px;
      text-align: center;
    }
    
    .back {
      position:relative;
      top: 20px;
      left: 20px;
      background: red;
    }
    .back2 {
      position:relative;
      top: 50px;
      left: 20px;
      background: orange;
    }
    
    .front {
      position: absolute;
      z-index:20;
      top: 60px;
      left: 60px;
      background: green;
    }
    <div class="back">
      <span >Parent div1</span>
      <div class="front">
        <span >dropdown</span>
      </div>
    </div>
    
    <div class="back2">
      <span >someOtherDiv</span>
    </div>

    As per your question you can't remove z-index from parent div in that case you can update greater z-index to parent div. Check updated snippet below...

    .back, .front, .back2{
      position: absolute;
      width: 100px;
      color: white;
      line-height: 100px;
      text-align: center;
    }
    
    .back {
      position:relative;
      top: 20px;
      left: 20px;
      background: red;
      z-index:10;
    }
    .back2 {
      position:relative;
      top: 50px;
      left: 20px;
      background: orange;
      z-index:9;
    }
    
    .front {
      position: absolute;
      z-index:20;
      top: 60px;
      left: 60px;
      background: green;
    }
    <div class="back">
      <span >Parent div1</span>
      <div class="front">
        <span >dropdown</span>
      </div>
    </div>
    
    <div class="back2">
      <span >someOtherDiv</span>
    </div>