Taming the Scrollbar Shift

Created: 2025-04-10
3 min read

A couple of months ago I noticed on my Windows computer that I noticed content layout shifts when navigating through this website. At first I did not understand what caused it, and more importantly, why. In the end it was because some pages would have enough content so a scrollbar would be shown while others did not and therefore switching between either would cause Content Layout Shift (CLS). That's the infamous scrollbar layout shift, and it's been driving developers crazy for years.

The Problem

On Windows, Chrome's scrollbars take up actual space in the viewport (unlike on macOS where they overlay content). When content becomes long enough to scroll, the scrollbar appears and poof - your layout shifts by about 17px. Buttons move, text reflows, and your pixel-perfect design goes out the window.

Solution 1: The Modern Way with scrollbar-gutter

CSS now has a property specifically designed for this problem:

css
1body { 2 scrollbar-gutter: stable; 3}

This reserves space for the scrollbar even when it's not visible. Clean, simple, and elegant! But... browser support isn't perfect yet (though it's getting better). For Windows Chrome this would however always show the scrollbar even if there is nothing to scroll.

Another issue with this approach is that when you use Tailwind (you should!), it means quite a lot of changes to globals.css which is something I did not want to do just to resolve this issue.

Solution 2: The Math Approach

You can calculate and account for scrollbar width:

css
1.container { 2 width: calc(100% - 17px); /* Approximate scrollbar width */ 3 margin-right: auto; 4 margin-left: 0; 5}

This works but feels a bit hacky, and the exact scrollbar width can vary between operating systems and browsers.

Solution 3: The better Tailwind Way

By coincidence I found the Tailwind plugin tailwind-scrollbar, which offers various options to style the scrollbar but it also has the scrollbar-none class which completely hides the scrollbar.

Here is how to install it:

shell
pnpm add -D tailwind-scrollbar@3.1.0

I am installing the latest compatible version with Tailwind 3 as the latest version of it only works with Tailwind 4.

Afterwards it needs to be added to the Tailwind config file (tailwind.config.js):

js
1plugins: [ 2 require('tailwind-scrollbar'), 3],

My Take

I have found the tailwind-scrollbar to be the cleanest and easiest approach. It just requires installing one package and adding a class to the root layout.