Prevent a page from scrolling while a dialog box is open | CSS tricks

Prevent a page from scrolling while a dialog box is open | CSS tricks

Bramus:

Chrome 144 has a small change overscroll-behavior: it now also works on non-scrollable scroll containers. While this change may seem trivial, it fixes an issue that developers have faced for ages: preventing a page from scrolling while a (modal)

has been opened.

YES! Way back in 2019, I collaborated with Brad Wu on “Prevent Page Scrolling When a Modal is Open” on this very topic. Apparently it only took a few months before we got our hands on the real HTML

element. In any case, you can see the problem with active scrolling when a “dialog box” is open:

The problem is that the dialog box itself is not a scroll container. If it were, we could hit overscroll-behavior: contain on it and done with it. Brad demonstrated his solution which included a JavaScript-like approach that uses the to fixed positioning when the dialog is in an open state:

That’s the tweak Bramus is talking about. In Chrome 144, that’s no longer the case. Going back to that first demo, we can do a couple of things to avoid all the JS mumbo-jumbo.

First, we declare overscroll-behavior on both the dialogue element and the background and set it to contain:

body {
  overscroll-behavior: contain;
}

#dialog {
  overscroll-behavior: contain;
}

You’d think that would be enough, but there’s a super important final step. That dialog needs to be a scroll container, which we can do explicitly:

#dialog {
  overscroll-behavior: contain;
  overflow: hidden;
}

Chrome 144 is obviously necessary:

The demo Bramus provided is much, much better because it covers the actual HTML

element and being ::backdrop:

Direct link →

#Prevent #page #scrolling #dialog #box #open #CSS #tricks

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *