Search code examples
htmlcssflexboxz-index

Flexbox items are overlapping z-index set on sibling elements


I have a flexbox with multiple children in it. Each flex-item has a child element that is being overlapped by the next sibling flex-item. How do you correct or account for this behavior?

Here is a demo of the behavior in question. There were several other questions on SO that suggested applying a greater z-index to the :first-child in the group. This worked - but only for the first element.

.container {
  display: flex;
  background: #eee;
  margin-top: 5%;
  height: 100px;
  z-index: 1;
}

.container .flex-item {
  _flex: 0 0 1;
  width: 25%;
  height: 80px;
  margin: 10px;
  position: relative;
  background: #ccc;
  z-index: 500;
}

.container .flex-item .widget {
  width: 70px;
  height: 70px;
  background-color: #004990;
  border-radius: 50%;
  position: absolute;
  top: -35px;
  right: -35px;
}
<div class="container">
  <div class="flex-item">
    <div class="widget"></div>
  </div>
  <div class="flex-item">
    <div class="widget"></div>
  </div>
  <div class="flex-item">
    <div class="widget"></div>
  </div>
  <div class="flex-item">
    <div class="widget"></div>
  </div>  
</div>

I have a codepen that exemplifies the desired functionality https://codepen.io/barrychapman/pen/QWKLbKw - but the only way I could get it to work was to apply sequentially decreasing z-index's on each element in the list.

How can I achieve this desired behavior without the need for the codepen example?


Solution

  • You can just remove the z-index from every item except the widgets bubbles. This will lead to the desired output of having the bubbles always on top of any container.

    .container {
      display: flex;
      background: #eee;
      margin-top: 5%;
      height: 100px;
    }
    
    .container .flex-item {
      flex: 0 0 1;
      width: 25%;
      height: 80px;
      margin: 10px;
      position: relative;
      background: #ccc;
    }
    
    .container .flex-item .widget {
      width: 70px;
      height: 70px;
      background-color: #004990;
      border-radius: 50%;
      position: absolute;
      top: -35px;
      right: -35px;
      z-index:1;
    }
    <div class="container">
      <div class="flex-item">
        <div class="widget"></div>
      </div>
      <div class="flex-item">
        <div class="widget"></div>
      </div>
      <div class="flex-item">
        <div class="widget"></div>
      </div>
      <div class="flex-item">
        <div class="widget"></div>
      </div>  
    </div>