Get "PHP 8 in a Nutshell" (Now with PHP 8.5)
Amit Merchant
Amit Merchant

A blog on PHP, JavaScript, and more

One CSS Trick to Eliminate Scrollbar Layout Shifts

When a webpage’s content exceeds the viewport height, browsers typically introduce a vertical scrollbar. This can lead to layout shifts, especially when navigating between pages or toggling content visibility, as the presence or absence of the scrollbar alters the available width for content.

For instance, I faced this issue in one of my apps where once the content overflows, the scrollbar appears, causing the text in the textarea to shift leftwards.

Without Scrollbar Gutter

To address this issue, you can use the scrollbar-gutter CSS property, which allows you to reserve space for the scrollbar, preventing layout shifts when it appears or disappears.

More specifically, you can set the scrollbar-gutter property to stable on the body element (or any other container element) to ensure that space for the scrollbar is always reserved.

In my case, I added this to the textarea element itself.

textarea {
  scrollbar-gutter: stable;
}

This way, the layout remains consistent regardless of whether the scrollbar is present or not. This can be seen in the following GIF, where the content of the textarea doesn’t shift when the scrollbar appears.

With Scrollbar Gutter

The scrollbar-gutter property is a fairly new addition to CSS and is supported (since December 2024) in most modern browsers. So, you can confidently use it to enhance the user experience on your web pages.

👋 Hi there! This is Amit, again. I write articles about all things web development. If you enjoy my work (the articles, the open-source projects, my general demeanour... anything really), consider leaving a tip & supporting the site. Your support is incredibly appreciated!

Comments?