CSS prevents page scrolling
CSS Disable Page Scrolling
In web development, sometimes we need to disable page scrolling, for example, to prevent users from continuing to scroll when a popup or menu is expanded. We can achieve this functionality using a few CSS properties and techniques. This article will detail how to disable page scrolling using CSS.
Using overflow: hidden
The simplest method is to use the CSS property overflow: hidden
to disable page scrolling. By adding this attribute to the html
and body
elements, you can disable page scrolling.
html, body {
overflow: hidden;
}
Using position: fixed
Another method is to use the position: fixed
attribute to fix the position of the page, thereby preventing scrolling.
html, body {
position: fixed;
width: 100%; /* Maintain original width */
}
Using JavaScript
In addition to the pure CSS method, we can also use JavaScript to prevent page scrolling. For example, when a popup appears, you can add a class name to prevent the page from scrolling.
<button id="openModal">Open popup</button>
<div id="modal" class="modal">
<div class="modal-content">
<p>This is a popup</p>
<button id="closeModal">Close</button>
</div>
</div>
.modal {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.modal-content {
background: white;
padding: 20px;
border-radius: 5px;
}
const openModalBtn = document.getElementById('openModal');
const closeModalBtn = document.getElementById('closeModal');
const modal = document.getElementById('modal');
openModalBtn.addEventListener('click', () => {
modal.style.display = 'block';
document.body.style.overflow = 'hidden';
});
closeModalBtn.addEventListener('click', () => {
modal.style.display = 'none';
document.body.style.overflow = 'auto';
});
In this example, when the “Open Popup” button is clicked, the popup is displayed and page scrolling is disabled. When the “Close” button is clicked, the popup disappears and the page scrolls.
Summary
Using the above methods, we can easily achieve the effect of preventing page scrolling. Choosing the appropriate method depends on specific needs and circumstances. Combining CSS and JavaScript can achieve richer interactive effects.