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.

5 Likes

Thank you. this didn’t work for me. On the upper-right I have a ‘voorraad’ button and this triggers an absolute positioned modal that’s essentially a duplicate of that section with some other content. Users can click and decide to not unclick and scroll, which can’t be done right now.

Do you have any other thoughts? Thanks!

It’s hard to tell what the issue on your installation is, without having a direct look @webmaat.

oops :wink: https://lg.webmaat.dev/en/

Everything works as intended on this site @webmaat.

When opening the modal, the site content won’t shift because of the now disabled but still visible scroll bar.
The only thing that shifts is your modal content which is expected due to the fixed position and 100% width.
In fact, this behaviour is only visible because of this very reason:

I’m not sure what you are trying to achieve here, but a modal might not be suitable for this case anyway.

I agree with Marius.

Having a simple absolutely positioned element and toggling this using an interaction will probably work better than a modal for your use case.

I guess you both are right. Using a modal isn’t good practice here. I must admit I need to plan time to really dig into the possibilities of interactions.