šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

CSS – prevent scroll of body but allow modal scroll

Let's say we have an HTML structure, with some main content and a modal, like the one below:

<body>
    <div><!-- main content here --> </div>
    <div class="modal><!-- modal content --> </div>
</body>

Both the main content and the modal have a lot of text, therefore they will be scrollable. However, we don't want to scroll the main content body while the modal is visible.

Given the way overflow scroll works, after the user scrolls to the end of the modal content the scroll will move to the body.
screenshot of prevent CSS scroll of body but allow modal scroll

This is what we want to prevent! We want to allow the full scrolling of the modal content, but we need to prevent the scroll of the body.

See the below video with the before and after example:

Solution: use the overscroll-behavior property to block the scrolling of the body

Even if it seems a complicated problem, the solution is quite simple.

We have the overscroll-behavior CSS property that deals exactly with situations like these. It comes with 3 possible values:

  • auto: scroll the element, and when reached the end of it pass the scroll to the parent
  • contain: scroll just the current element
  • none: don't scroll either the current element or its parent

So, all we need to do is to apply overscroll-behavior to the modal:

.modal {
    /*prevent the passing of the scrolling to the parent */
    overscroll-behavior: contain;

    /*rest of the styling here */
    width: 300px ;
    height: 200px;
    border: 1px solid;
    background-color: lightblue;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    padding: 0.5rem;
    overflow: auto;
}

Please note that we can set overscroll-behavior also just the X or Y axis:

overscroll-behavior-x: auto;
overscroll-behavior-y: contain;

/*or with the shorthand*/
overscroll-behavior: auto contain;

The overall browser support for overscroll-behavior is great.

You can check out the full codepen example here.

Also I've made this example for how to use the scrollIntoView() API with React.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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