Preventing Layout Shifts When Opening a Modal
Published on: 2024-03-12
In web development, modals are a common feature that allows us to display content in a layer above the page which often requires disabling background scrolling to provide a better user experience. However, this can lead to an annoying layout shift due to the disappearance of the scrollbar. In this article, we'll explore a solution to this problem using HTML, CSS, and JavaScript.
The Problem
When a modal is opened, we often set the overflow
property of the body
to hidden
to prevent background scrolling. This works as expected, but it hides the scrollbar, causing a sudden layout shift. This shift can be jarring for users and is generally considered a bad practice in terms of UX and performance.
The Solution
The solution to this problem involves two steps:
- Calculating the width of the scrollbar.
- Adding a padding to the body equal to the width of the scrollbar when the modal is opened.
By doing this, we can effectively reserve the space for the scrollbar, even when it's not visible. This prevents the layout shift while still disabling background scrolling.
Here's how we can implement this in JavaScript:
// Calculate the scrollbar width
const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
// Function to open the modal
function openModal() {
document.body.style.overflow = "hidden";
document.body.style.paddingRight = `${scrollbarWidth}px`;
}
// Function to close the modal
function closeModal() {
document.body.style.overflow = "auto";
document.body.style.paddingRight = "0px";
}
In the openModal
function, we set the overflow
of the body to hidden
and add a right padding to the body equal to the scrollbar width.
In the closeModal
function, we reset the overflow
and padding of the body.
Conclusion
Preventing layout shifts when opening a modal is crucial for providing a smooth user experience. By calculating the scrollbar width and adjusting the body padding accordingly, we can prevent these shifts while still disabling background scrolling. This approach is a testament to the flexibility and power of HTML, CSS, and JavaScript.