Explore Bato Web Agency Webflow Certified Partner Profile Explore Bato Web Agency Webflow Certified Partner Profile

How do you lock background scrolling when a mobile modal is open?

Illustration without a description Illustration without a description

Lock background scrolling by applying one reversible page state while the modal remains open, and keep the modal’s own content scrollable. A native dialog opened with showModal() provides built-in modality, but page scroll handling still deserves device testing. Save the page position before using a fixed-body lock.

 

A simple overflow: hidden rule on the document root works in many browsers. When iOS behavior or a complex layout still allows movement, fix the body at the negative scroll offset, set its width, then restore styles and scroll position on close. Do not reset the reader to the top of the page.

 

let savedY = 0;

function lockPage() {
savedY = window.scrollY;
document.body.style.position = 'fixed';
document.body.style.top = `-${savedY}px`;
document.body.style.width = '100%';
}

function unlockPage() {
document.body.style.position = '';
document.body.style.top = '';
document.body.style.width = '';
window.scrollTo(0, savedY);
}

 

Give the dialog panel a maximum height based on the viewport and overflow: auto so long content remains reachable. Add overscroll-behavior: contain where supported to reduce scroll chaining when the panel reaches an edge. Do not block pinch zoom or touch gestures across the entire page.

 

Scroll locking is only one part of a modal. Move focus inside when it opens, keep focus within the active dialog, support Escape when dismissal is allowed, and restore focus to the trigger. Mark the background inert so keyboard and assistive-technology users cannot operate hidden page controls.

 

Test at the top, middle and bottom of a long page. Try dragging inside short and long modal content, reaching both scroll boundaries and closing through every supported path. Confirm that the page stays still behind the modal and returns to the saved position without a visible sideways shift from a disappearing scrollbar.