Fix Scrollbar Layout Shifts with Just CSS

Layout shifts caused by the appearance of scrollbars can be a frustrating user experience issue. As an example, here's a little gif of what happens to your content by default when a scrollbar appears:

Showing the content shift of a scrollbar in the auto layout

Fortunately, CSS provides a simple solution with the scrollbar-gutter property. Here's how to implement it:

.container {
    scrollbar-gutter: stable;
}

This single line of CSS can prevent layout shifts when scrollbars appear.

Showing the content remain static when using scrollbar-gutter: stable

And in case you are interested, here are the different values for scrollbar-gutter:

  • auto (default): The scrollbar takes up space when it appears, potentially causing layout shifts.

  • stable: Space for the scrollbar is always reserved, even when the scrollbar isn't present. This prevents layout shifts but may leave space when no scrollbar is needed.

  • stable both-edges: Similar to stable, but reserves space on both sides of the container. This can be useful for maintaining centered content.

To play around with each setting, here's a CodePen I created:

In this example, you can toggle the overflow for each setting and observe how the layout behaves. This visual demonstration should help clarify the impact of each scrollbar-gutter value on your layout.

CSS
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.