Skip to content

Instantly share code, notes, and snippets.

@am-on
Created January 25, 2024 12:06
Show Gist options
  • Save am-on/516443dfc7e927ea948f34e54f06cadb to your computer and use it in GitHub Desktop.
Save am-on/516443dfc7e927ea948f34e54f06cadb to your computer and use it in GitHub Desktop.
Disable body scroll on modal open
  1. Add class only present when modal is opened like <div class="modal-opened">
  2. Prevent scrolling when modal is opened with CSS:
    html body:has(.modal-opened) {
      overflow: hidden;
    }
  3. On modal open the scrollbar will disappear and cause a small layout shift. The easiest way to avoid this is using scrollbar-gutter. With this the page always reserves spacing for scrollbar even if the page doesn't need it.
    html {
      scrollbar-gutter: stable;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment