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
Release: 2024-12-26 10:06:16
Original
566 people have browsed it

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;
}
Copy after login

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;
}
Copy after login

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;
}
Copy after login

JS:

const b = document.body;
b.style.setProperty('--st', -(document.documentElement.scrollTop) + "px");
b.classList.add('noscroll');
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template