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:
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.
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 tostable
, 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.