Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a modal background fill the entire page, even when there is a scroll?

I have a modal for editing some content, and while I want the background for the modal to fill the entire visible screen, the form (or modal content, whatever you want to call it) has a fixed height. Issues arise when resizing the window, and the page underneath the modal is the same height as the window, but smaller than the form. What ends up happening is the background only covers a visible portion of the screen, and never the whole thing.

JSFiddle which shows what happens: https://jsfiddle.net/yzhm7v12/3/
When you scroll, part of the background doesn’t show at the bottom. How can I make it stretch to fill the entire height of the body element?

document.addEventListener('click', function() {
  const modal = document.querySelector('.modal');
  modal.classList.toggle('hidden');
});
* {
  margin: 0;
  padding: 0;
}

body {
  height: 100%;
}

.flex {
  width: 100%;
  height: 100vh;
  background-color: #999999;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.modal {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
}

.modal.hidden {
  display: none;
}

.modal_content {
  margin: auto 0;
  width: 100px;
  height: 300px;
  background-color: #999999;
  border: 3px solid red;
}
<body>
  <div class="flex">
    <p>Click anywhere in the document to add/remove the modal</p>
    <p>Resize the window so the modal is too tall, then try to scroll</p>
  </div>
  <div class="modal hidden">
    <div class="modal_content">
    </div>
  </div>
</body>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could resolve this issue by setting on the modal a position fixed instead of an absolute one as you did. Like so:

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading