Search code examples
htmlcssoverflowcss-position

Position absolute div not appearing in front of overflow-y scroll content


Basically, I need the "modal" div to fill the height/width of the .container div no matter where you scroll in the div. For some reason, the .modal div keeps appearing in a stack with the .inner-wrapper div even though it is position absolute.

Why does it not fill the parent .container div?

I'd like to avoid JS, if possible.

I've tried playing with the position properties on all the divs involved. I've also tried playing with the translate property. I was thinking that display: flex may have something to do with this too, but was proven wrong. My guess is that this issue is related to the overflow-y: scroll.

$(".open-btn").click(function() {
  $(".modal").toggle();
});
.container {
  width: 300px;
  height: 300px;
  position: relative;
  border: 2px solid black;
  overflow-y: scroll;
}

.inner-wrapper {
  width: 100%;
  height: 800px;
  background: rgba(34, 34, 12, 0.3);
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-end;
  align-items: flex-end;
}

.open-btn {
  display: block;
  width: 100px;
  height: 30px;
}

.modal {
  display: none;
  width: 90%;
  height: 90%;
  background: green;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="modal"></div>
  <div class="inner-wrapper">
    <button class="open-btn">Open</button>
  </div>
</div>

See Codepen link below for context: https://codepen.io/nss5161/pen/abaPZvy?editors=1100

Position on Scroll Div Diagram Multiple Position on Scroll Div Diagram


Solution

  • -- Edited --

    I hope that's what you need.

    $(".open-btn").click(function() {
      $(".modal").toggle();
    });
    .main {
      width: 300px;
      height: 300px;
      position: relative;
    }
    
    .container {
      width: 300px;
      height: 300px;
      position: relative;
      border: 2px solid black;
      overflow-y: scroll;
    }
    
    .inner-wrapper {
      width: 100%;
      height: 800px;
      background: rgba(34, 34, 12, 0.3);
      display: flex;
      flex-flow: row nowrap;
      justify-content: flex-end;
      align-items: flex-end;
    }
    
    .open-btn {
      display: block;
      width: 100px;
      height: 30px;
    }
    
    .modal {
      display: block;
      width: 90%;
      height: 90%;
      background: green;
      position: absolute;
      top: 5%;
      left: 3%;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="main">
      <div class="modal"></div>
      <div class="container">
        <div class="inner-wrapper">
          <button class="open-btn">Open</button>
        </div>
      </div>
    </div>