I have a website were some pages are long enough that there is a vertical scrollbar on the body, and some pages are too short to have one.
I also have a dialog boxes on my website which disable scrolling by setting overflow-y: hidden
on the document element.
In order to prevent layout shifts when the dialogs are opened and the scrollbar is removed, I want to use scrollbar-gutter: stable
.
However, in the cases were scrollbar gutter is applied to pages which aren`t long enough to have a scrollbar, you still get the gutter which of course causes the page look weird.
Therefore I need a way to only apply the scrollbar gutter if the page can have a scrollbar. How do I do this?
2
Answers
You can detect it with simple JavaScript.
But I don’t recommend you to use scrollbar-gutter since Safari does not support it.
Instead you can try to play with width: 100vw, thats way your page will always have constant width.
Step-by-Step Solution to Apply
scrollbar-gutter
ConditionallyStep 1: Check for Scrollbar Necessity with JavaScript
First, you need to determine if the page is long enough to require a scrollbar. You can do this by comparing the viewport height with the total height of the document’s content.
This script checks if the height of the content (
document.documentElement.scrollHeight
) exceeds the height of the viewport (window.innerHeight
). If so, it means a scrollbar is necessary, and it adds a classhas-scrollbar
to the body.Step 2: Apply CSS Conditionally
Now, use this class to apply
scrollbar-gutter
only when the scrollbar is needed.With this CSS, the
scrollbar-gutter: stable
property is applied only to the body element that has thehas-scrollbar
class, which is added dynamically by the JavaScript only on pages that are tall enough to need a scrollbar.Conclusion
By combining this JavaScript and CSS, you can ensure that
scrollbar-gutter
is applied only when necessary, avoiding the weird layout issues on shorter pages.Please note that this message was generated by an artificial intelligence system currently in its beta phase.
It is part of a script designed to automatically adopt the post format and provide solutions to the described problem.
While I strive to offer accurate and helpful advice, I cannot guarantee the effectiveness of these solutions due to the automated nature of this response.
My apologies if these steps do not resolve your issue, and I’m not directly responsible if the provided solutions are not successful.
Your understanding is greatly appreciated.