Preventing horizontal layout shift on a website with CSS

Preventing horizontal layout shift on a website with CSS

Published on 12.03.2024

Have you ever been on a website and noticed that the whole page seems to jump to the side when you move between pages? That’s what we call a horizontal layout shift, and it’s not a fun experience. It happens when a vertical scrollbar pops up and nudges your content over. Not cool, right?

#The Problem

Imagine you’re happily browsing a website, and then, out of nowhere, everything shifts to the left. Why? Because a scrollbar just appeared. It’s like when you’re watching a movie and someone suddenly stands up in front of you. The longer the webpage, the more likely you’ll get this unwanted surprise. It’s especially noticeable and annoying when you’ve got a neat centered design that suddenly goes off-balance.

#Solution: Always Show the Scrollbar

Now, here’s a nifty trick: make that scrollbar stick around permanently. Yep, even when you don’t need it to scroll. This way, your layout stays the same—no more jumping content. You can do this with a simple line of CSS. Just add overflow-y: scroll to your body tag, and you’re all set. Here’s how it looks in code:

body {
  overflow-y: scroll;

But what if you don’t want the scrollbar to take up space on your whole page? No problem! Just apply this trick to the specific element that’s causing the layout shift.

Oh, and if you’re worried about the scrollbar cramping your style, you can give it a makeover. That’s right, you can customize the scrollbar’s design to match your website’s vibe. No more ugly, default scrollbars ruining your aesthetic.

By keeping the scrollbar visible, you’re creating a smoother experience for your users. No more jumpy transitions, just smooth sailing from one page to the next. It’s a small change with a big impact on usability and visual stability.