Prevent Layout Shift when using Modals

Triggering a modal does remove the scrollbar to prevent user scroll, in case this setting is toggled from the block options.
In most cases (at least for me), it makes sense to take advantage of this option, to deliver a better user experience.

The problem is, that the entire page layout needs to expand to the width the scrollbar took.
When the modal gets closed, the scrollbar needs to be re-added, so this kind of issue will actually occur twice per modal interaction.

In some cases, users won’t even notice, in other cases this can lead to a very bad experience.
It also depends on the browser & operating system and how the scrollbar is designed.

I’ve already read about this issue on the Facebook group 1-2 times, where it was suggested to be a bug.
So, I just want to clear things a bit up.
Is there a way to prevent this browser behavior? There is.

First, I want to demonstrate the difference, before and after.
When opening and closing the modal, you need to pay attention to the page content.

Default behavior
Optimized behavior

It’s not a drastic example, it can be a lot worse. But I think you get the idea.

Hot to achieve it?
It’s actually just one simple CSS rule:

<style>
  html {
	scrollbar-gutter: stable;
  }
</style>

This rule applies to your entire site, not only to the modal block in particular.
It’s the general scrollbar behavior then. So you need to decide which route you prefer.

Please check Browser Compatibility first, before using in a project.
But, in case it’s not supported, it can’t break anything.

4 Likes