Always add html {overflow-y: scroll}, to prevent layout shift (CLS)

Updated: 25th December 2022
Tags: css html

In early 2012, I wondered why some of my pages had scrollbar and others - not. Logically, I found out that pages with little content don't have scrollbar. But while I was young, I thought this doesn't make any sense. So I quickly found out how to fix this:

html {overflow-y: scroll}
/* if you use bootstrap css framework use body, so it works fine with modals
body {overflow-y: scroll}

Fixes this issue. As I grow, I add this snippet to all my websites.

One of my new websites doesn't have it. And it causes layout shift.

Cumulative Layout Shift (CLS) is an important, user-centric metric for measuring visual stability because it helps quantify how often users experience unexpected layout shifts—a low CLS helps ensure that the page is delightful.

What's more, when you have a lot of pages, and they load not instantly, even if you have long text, browser will render the first few milliseconds without scrollbar, and only after it recognizes it is long text for scrollbar, then it will add it, which causes layout shift.