Joshua Wallace

Search

Engineer & Developer

Prevent the scrollbar from causing layout shifts using CSS

When working on this site, I noticed that the content was shifting to the left when I went from any other page on the site to my contact page. The only real difference between the pages was that the contact page was short, and not scrollable. This behaviour was only on Google Chrome, and not Firefox - so it definitely was not an issue with my CSS. So, it had to be the scrollbar. Google Chrome reserves spacing for the scrollbar when the page is scrollable, this means if you navigate from a page which does not exceed the viewport height, to a page which does, the scrollbar will shift the content to the left to make room for itself.

The fix to this is quite simple - a single line of CSS and assuming a somewhat modern browser is used. The scrollbar-gutter property allows you to control the space reserved for the scrollbar. Setting it to stable will prevent the content from shifting when the scrollbar is present.


html {
    scrollbar-gutter: stable;
}

Adding this to the root of the stylesheet, and the issue is quickly resolved.