Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of 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:

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

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.

Home Screencasts Best of Newsletter Search X