Search code examples
htmlcssless

Why is the child div clipped even if overflow-y of the parent is auto or visible


There is a parent div whose position is set to relative. And there is a child div that has position absolute. I want to place it on top of the parent div but it hides the content as parent's overflow-x and overflow-y are auto.

.container {
  width: 200px;
  height: 200px;
  background-color: gray;
  position: relative;
  z-index: 1;
  overflow-x: auto;
  overflow-y: auto;
}

.popover-container {
  background-color: red;
  width: 100px;
  height: 100px;
  margin: 40px;
}

.popover {
  font-size: 20px;
  background-color: green;
  display: inline-block;
  position: absolute;
  top: -10px;
  z-index: 3;
}
<div class="container">
  <div class="popover-container">
    <div class="popover">Hello</div>
  </div>
</div>

When I set the parents overflow-x and overflow-y both to visible then it works. But if I only set the overflow-y to visible it is hidden.

I cannot set overflow-x to visible it works fine.

Is there anyway to achieve this without setting overflow-x to visible?


Solution

  • Found the answer in this beautiful blogpost:

    We need to add a parent div to container and after make the popover position relative to this grand parent.

    .parent-container {
      position: relative;
    }
    
    .container {
      width: 200px;
      height: 200px;
      background-color: gray;
      z-index: 1;
      overflow-x: auto;
      overflow-y: auto;
    }
    
    .popover-container {
      background-color: red;
      width: 100px;
      height: 100px;
      margin: 40px;
    }
    
    .popover {
      font-size: 20px;
      background-color: green;
      display: inline-block;
      position: absolute;
      top: -10px;
      z-index: 3;
    }
    <div class="parent-container">
      <div class="container">
        <div class="popover-container">
          <div class="popover">Hello</div>
        </div>
      </div>
    </div>