Search code examples
htmlcssz-indexoverlapping

Z-index doesn't overlap to the same DIVs


The problem is the overlapping yellow blocks– they should always be on top.

Yes, I know I can draw the yellow blocks and set them using absolute positioning. But... Can I solve this without changing the HTML structure?

Codepen Link

.container {
  position: relative;
  margin-bottom: 10px;
  z-index: 1;
}
.green {
  position: sticky;
  left: 0;
  height: 300px;
  width: 300px;
  background: green;
  z-index: 2;
}
.blue {
  position: relative;
  background: blue;
  height: 30px;
  width: 30px;
  left: 50%;
  top: 50%;
  z-index: 3;
}
.yellow {
  position: absolute;
  left: 0;
  top: 30px;
  height: 250px;
  width: 250px;
  background: yellow;
  z-index: 4;
}
<div class="container">
  <div class="green">
    <div class="blue">
      <div class="yellow"></div>
    </div> 
  </div>
</div>
<div class="container">
  <div class="green">
    <div class="blue">
      <div class="yellow"></div>
    </div> 
  </div>
</div>
<div class="container">
  <div class="green">
    <div class="nested">
      <div class="yellow"></div>
    </div> 
  </div>
</div>


Solution

  • html

    <div class="container1">
          <div class="green">
            <div class="blue">
              <div class="yellow"></div>
            </div> 
          </div>
        </div>
        <div class="container2">
          <div class="green">
            <div class="blue">
              <div class="yellow"></div>
            </div> 
          </div>
        </div>
        <div class="container3">
          <div class="green">
            <div class="nested">
              <div class="yellow"></div>
            </div> 
          </div>
        </div>
    

    CSS

      .container1 {
          position: relative;
          margin-bottom: 10px;
          z-index: 8;
        }
        .container2 {
          position: relative;
          margin-bottom: 10px;
          z-index: 7;
        }
        .container3 {
          position: relative;
          margin-bottom: 10px;
          z-index: 6;
        }
        .green {
          position: sticky;
          left: 0;
          height: 300px;
          width: 300px;
          background: green;
          z-index: 2;
        }
        .blue {
          position: relative;
          background: blue;
          height: 30px;
          width: 30px;
          left: 50%;
          top: 50%;
          z-index: 3;
        }
        .yellow {
          position: absolute;
          left: 0;
          top: 30px;
          height: 250px;
          width: 250px;
          background: yellow;
          z-index: 1000;
        }
    

    I am so sorry but have just found a solution to that problem a little bit by changing the HTML code. Can you explain about the absolute position? to which parent element do you want to set yellow block?