How to Disable Page Scrolling when Modal Dialog is Opened

Published on December 15, 2019

When a fixed-position modal dialog is opened, scrollbars on the page can be removed by dynamically setting overflow: hidden CSS for the <body> tag

Page scrolling looks weird when a fixed-position modal dialog is opened. The user can scroll through the background content, however it serves no purpose as dialog is fixed in the front.

Ideally there should no scrollbars in the page when a modal dialog is seen.

Unfortunately there is no pure CSS solution to this problem. It needs Javascript to dynamically set overflow: hidden to <body> when modal is opened, and reset overflow to visible when modal is closed.

/* when modal is opened */
document.querySelector("#open-modal-button").addEventListener('click', function() {
    document.querySelector("#modal-container").style.display = 'block';
    document.querySelector("body").style.overflow = 'hidden';

/* when modal is closed */
document.querySelector("#close-modal-button").addEventListener('click', function() {
    document.querySelector("#modal-container").style.display = 'none';
    document.querySelector("body").style.overflow = 'visible';

Setting overflow: hidden to any element clips the overflown content, and so the scrollbar gets hidden too. Setting overflow: visible makes the overflown content as visible, and scrollbar, if present, will be shown.


View Demo

Download Codes

In this Tutorial