Home > Web Front-end > CSS Tutorial > How to Disable Body Scrollbar Without Hiding It?

How to Disable Body Scrollbar Without Hiding It?

Barbara Streisand
Release: 2024-12-08 17:28:14
Original
805 people have browsed it

How to Disable Body Scrollbar Without Hiding It?

Disabling HTML/Body Scrollbar While Preserving Visibility

For an optimal lightbox experience, one may desire to temporarily disable the parent element's scrollbar without concealing it. To achieve this, consider the following approach:

Fix Parent Element:

When opening the lightbox, assign the following CSS properties to the page underlying the overlay:

body {
  position: fixed;
  overflow-y: scroll;
}
Copy after login

This fixes the page's position and restricts vertical scrolling to the page itself, while maintaining the scrollbar's visibility.

Reset on Lightbox Close:

When closing the lightbox, restore the original CSS properties:

body {
  position: static;
  overflow-y: auto;
}
Copy after login

Handling Existing Scroll:

To preserve the page's current scroll position, use JavaScript to obtain the document's scrollTop value before opening the lightbox and assign it as the top property of the body element:

.noscroll {
  position: fixed;
  top: var(--st, 0);
  inline-size: 100%;
  overflow-y: scroll;
}
Copy after login
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 to Disable Body Scrollbar Without Hiding It?. 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