Thiago P
Thiago P

Reputation: 285

Fixed modal wont scroll when overflowing the viewport

Issue

I've made a fixed modal to display over the main content of a page. The modal has content whose height may end up larger than the viewport and thus needs to scroll, but its just not working.

Contents of Modal

Within the modal are

  1. An empty overlay/background div with a grayed background, that takes up the full width and height of the modal.
  2. The content itself which may end up having a height greater than the viewport.

JS Fiddle

Here is a JS Fiddle demonstrating the problem. I've added border coloring to better help differentiate individual elements.

https://jsfiddle.net/mLjs49ms/7/

Upvotes: 3

Views: 6714

Answers (1)

Chiller
Chiller

Reputation: 9738

You need to add this css properties to modal__content :

  position:relative;
  overflow:auto;
  height:100%;
  • z-index was not being applied because the position was static so you need to add position:relative
  • and to activate the scroll you need to add both overflow:auto and a fixed height of 100%
  • Without forgetting you should fix the height of the modal parent modal to 100% as well

See result:

html,
body {
  width: 100%;
}

html {
  height: 100%;
}

body {
  min-height: 100%;
  font-family: consolas;
}

.main {
  border: 2px solid blue;
}

.modal {
  z-index: 10;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 2px solid red;
}

.modal__overlay {
  z-index: 1;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(138, 138, 138, 0.5);
  border: 2px dashed green;
}

.modal__content {
  z-index: 2;
  border: 2px dotted blue;
  position: relative;
  overflow: auto;
  height: 100%;
}

.simulate-content {
  width: 120px;
  height: 200px;
  margin: 12px auto;
  padding: 12px;
  text-align: center;
  font-weight: bold;
  background-color: rgb(255, 50, 50);
}
<body>
  <!-- PLACEHOLDER CONTENT -->
  <div class='main'>
    <h3> BODY CONTENT </h3>
    <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
      dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
  </div>

  <!-- THE MODAL -->
  <div class='modal'>
    <div class='modal__overlay'></div>
    <div class='modal__content'>
      <p class='simulate-content'>MODAL CONTENT 1 of 5</p>
      <p class='simulate-content'>MODAL CONTENT 2 of 5</p>
      <p class='simulate-content'>MODAL CONTENT 3 of 5</p>
      <p class='simulate-content'>MODAL CONTENT 4 of 5</p>
      <p class='simulate-content'>MODAL CONTENT 5 of 5</p>
    </div>
  </div>
</body>

Upvotes: 6

Related Questions