Skip to main content Accessibility Feedback

Prevent scrollbar jump

With modal components, it’s common/expected to prevent the background from scrolling.

/**
 * Prevent background scrolling with a modal dialog is open
 */
html:has(dialog[open]:modal) {
	overflow: hidden;
}

However, if your page was long enough that there were visible scrollbars, they disappear when you set overflow to hidden, which causes the layout to shift horizontally.

Sometimes it’s hard to see behind the modal backdrop, but it’s often visible and a bit jarring.

Here’s an example on CodePen.

The scrollbar-gutter CSS property tells the browser to reserve space for a scrollbar, even when one isn’t visible. It can be used to prevent that visual shift.

A value of stable reserves space in the default scrollbar position. A value of stable both-edges holds space on both sides of the viewport. And a value of auto is like not having the property at all.

/**
 * Hold space for scrollbar to prevent jumping on pages.
 */
html {
	scrollbar-gutter: stable;
}

Here’s an updated demo with scrollbar-gutter implemented. You can also see it in action with Kelp’s modal dialogs and off-canvas drawers.

The scrollbar-gutter property is now a baseline feature, and time of writing.

People still using older browsers will see the jump, but I think this is a nice progressive enhancement, with an acceptable default behavior for unsupported browsers.