Replies: 1 comment
-
How Radix Prevents Layout Shift When Hiding ScrollbarRadix uses The TrickWhen locking scroll, Radix:
This keeps the total width identical. Implementation// Get scrollbar width
const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
// Before opening dialog
document.body.style.paddingRight = `${scrollbarWidth}px`;
document.body.style.overflow = "hidden";
// After closing dialog
document.body.style.paddingRight = "";
document.body.style.overflow = "";Radix uses react-remove-scrollUnder the hood, Radix Dialog uses import { RemoveScroll } from "react-remove-scroll";
<RemoveScroll>
<DialogContent />
</RemoveScroll>The CSS approach (without JS)For simpler cases: html {
overflow-y: scroll; /* Always show scrollbar track */
}
/* Or use overlay scrollbars (no width) */
html {
overflow-y: overlay; /* Deprecated but works */
scrollbar-gutter: stable;
}Why scrollbar-gutter alone is not enough
Full solutionfunction lockScroll() {
const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
document.body.dataset.scrollLocked = "true";
document.body.style.setProperty("--scrollbar-width", `${scrollbarWidth}px`);
}
// CSS
body[data-scroll-locked="true"] {
overflow: hidden;
padding-right: var(--scrollbar-width);
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm trying to understand the technique Radix UI uses on their website to make the scrollbar behave as if it doesn't exist. Specifically:
There is 0 layout shift, whether the page has a scrollbar or not.
They lock scroll without causing layout changes.
The page looks the same whether it is scrollable or not.
I'm especially interested in how Radix Dialog removes the page scrollbar without leaving any empty space on the body behind the dialog.
Normally, when overflow: hidden is applied to , the scrollbar disappears and the viewport becomes wider, causing:
Content to shift horizontally
Or a blank/white space to appear on the right side
But Radix’s Dialog somehow prevents this completely. I want to understand the exact mechanism they use to hide the scrollbar while keeping the page width visually identical, preventing any space from appearing where the scrollbar used to be.
Note: For anyone recommending it, I don’t think scrollbar-gutter: stable is the fix for this.
Beta Was this translation helpful? Give feedback.
All reactions