Skip to content

Modal

Prevent Page Scrolling When a Modal is Open

Source: CSS-Tricks and comment on overscroll-behavior CSS property

In CSS:

css
body.modal-open {
  height: 100vh;
  overflow-y: hidden;
  overscroll-behavior: contain;
}

body {
  height: auto;
  overflow-y: auto;
  overscroll-behavior: auto;
}

In JS:

js
/* Prevent scrolling when a modal is open for example */
function preventScroll() {
  const body = document.body;
  body.style.height = '100svh';
  body.style.overflowY = 'hidden';
  body.style.overscrollBehavior = 'contain';
}

/* Re-enable scrolling when the modal is closed */
function allowScroll() {
  const body = document.body;
  body.style.height = 'auto';
  body.style.overflowY = 'auto';
  body.style.overscrollBehavior = 'auto';
}