Preserving Scrollbar Visibility While Disabling Scrolling
Although it's possible to hide scrollbars using overflow: hidden, this approach can create visual shifts on your website. If you want to disable scrolling without compromising visibility, here's how:
Fix Page Position:
If the page beneath the overlay can be fixed at the top, apply the following CSS when opening the overlay:
body { position: fixed; overflow-y: scroll; }
This will retain the scrollbar visibility but prevent content scrolling. To restore scrolling upon overlay closure, use this CSS:
body { position: static; overflow-y: auto; }
Preserve Scroll Position:
If the page has been scrolled beforehand, obtain document.documentElement.scrollTop using JavaScript. Assign this value as the top property of the body element dynamically. This will maintain the current scroll position throughout the overlay's duration.
CSS:
.noscroll { position: fixed; top: var(--st, 0); inline-size: 100%; overflow-y: scroll; }
JS:
const b = document.body; b.style.setProperty('--st', -(document.documentElement.scrollTop) + "px"); b.classList.add('noscroll');
The above is the detailed content of How Can I Disable Scrolling While Keeping the Scrollbar Visible?. For more information, please follow other related articles on the PHP Chinese website!