Eliminate Layout Shift: Stabilize Scrollbars for Popovers and Dialogs with CSS `scrollbar-gutter`
Prevent disruptive layout shifts when hiding scrollbars for popovers or dialogs. Learn how CSS `scrollbar-gutter: stable` reserves space, ensuring a seamless user experience.
A common challenge in web development arises when opening popovers or dialogs: if the scrollbar is hidden using overflow: hidden, the page content can abruptly shift horizontally to fill the vacated space. This visual disturbance, known as layout shift, can negatively impact user experience.
The solution involves the CSS scrollbar-gutter: stable property. By applying this rule to your scroll container (typically the <body> element), you instruct the browser to reserve space for the scrollbar, even when it is not actively visible. This proactive space reservation effectively prevents jarring horizontal content shifts.
Here's how to implement this robust solution:
body {
scrollbar-gutter: stable;
&:has(:popover-open) {
overflow: hidden;
}
}
Observe the problem in action without scrollbar-gutter: stable:

Now, see the problem resolved with scrollbar-gutter: stable applied, ensuring a smooth transition:

By integrating scrollbar-gutter: stable into your CSS, you can significantly enhance the perceived performance and polish of your web applications, ensuring a consistent and professional user interface during dynamic element interactions.