Using CSS to prevent the user from scrolling

Sam RuebyWeb Development 3 Comments

I was creating a mobile menu for a project today. The normal, click-the-hamburger, expose a drawer with menu items, etc. I mocked this up in JsFiddle.

Screenshot of a mobile menu with a drawer

I darkened the background by making a simple overlay:

.mobileNavOverlay {
    position: fixed;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, .7);
    z-index: 2;
    top: 0;
    left: 0;
}

But I noticed that on mobile, you can still scroll the page (i.e. the body) even when the overlay was over the content. That’s not a deal breaker, but it is distracting. It took me a while to figure out how to prevent it, but here’s the solution.

.noScroll {
    overflow: hidden;
    position:fixed;
}

Setting overflow to hidden wasn’t a surprise, that’s what I originally guessed but I was surprised you’re still able to scroll the page while the overlay is displaying with this rule. The key is “position: fixed.” This successfully prevented the ability to scroll, which has to be set on the body element. Here is JsFiddle demonstrating this. Notice you’re unable to scroll once the class is applied.