Home > Web Front-end > CSS Tutorial > How Can I Prevent Scrollbar Scrolling Without Hiding the Scrollbar?

How Can I Prevent Scrollbar Scrolling Without Hiding the Scrollbar?

Linda Hamilton
Release: 2024-12-09 13:45:15
Original
943 people have browsed it

How Can I Prevent Scrollbar Scrolling Without Hiding the Scrollbar?

Preventing Scrollbar Scrolling Without Hiding

A common challenge when implementing lightboxes is the need to temporarily disable the scrollbar on the parent page without resorting to overflow: hidden;. This solution can cause undesired jumps and space occupation.

Thankfully, there is a viable approach to disable scrollbars while still displaying them. By utilizing a fixed positioning for elements beneath the overlay, it's possible to achieve this effect. When the overlay is activated, apply the following styles to the body:

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

This will display the scrollbar but disable its functionality. To revert this change upon closing the overlay, simply restore the original styles:

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

In cases where the page has already been scrolled, capturing the current scroll position via JavaScript and setting it as the top property of the body element ensures the page remains in its current scroll position when the overlay is activated. This can be achieved with the following CSS and JS:

.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

By implementing this approach, you can effectively disable scrollbars without hiding them, maintaining the desired functionality for both the lightbox and the parent page.

The above is the detailed content of How Can I Prevent Scrollbar Scrolling Without Hiding the Scrollbar?. 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