Home >Web Front-end >CSS Tutorial >How Can I Disable Scrolling While Keeping the Scrollbar Visible?

How Can I Disable Scrolling While Keeping the Scrollbar Visible?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-26 10:06:16560browse

How Can I Disable Scrolling While Keeping the Scrollbar Visible?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn