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

How to Disable Body Scrollbar Without Hiding It?

Barbara Streisand
Barbara StreisandOriginal
2024-12-08 17:28:14800browse

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;
}

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;
}

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;
}
const b = document.body;
b.style.setProperty('--st', -(document.documentElement.scrollTop) + "px");
b.classList.add('noscroll');

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!

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