Sometimes in web design, you want to temporarily disable scrolling on a page or a specific element—for example, when displaying a modal, loading overlay, or side menu. CSS offers simple, effective ways to disable both vertical and horizontal scrolling with just a few lines of code.
In this guide, you’ll learn how to disable scrolling using CSS, along with best practices and common use cases.
✅ Method 1: Disable Scrolling on the Whole Page
To disable scrolling for the entire page, set the overflow
property of the body
or html
to hidden
.
📌 CSS:
body {
overflow: hidden;
}
✅ What it does:
- Prevents both vertical and horizontal scrolling
- Locks the scroll bar and page position
🧠 Use Case:
- When a modal or full-screen menu is open
- To freeze page content temporarily
✅ Method 2: Disable Only Vertical or Horizontal Scrolling
You can selectively disable scrolling on one axis:
🔹 Disable Vertical Scroll Only:
body {
overflow-y: hidden;
}
🔹 Disable Horizontal Scroll Only:
body {
overflow-x: hidden;
}
✅ Method 3: Disable Scrolling on a Specific Element
Want to lock scrolling on a div instead of the entire page?
📌 CSS:
.scroll-locked {
overflow: hidden;
height: 100px; /* or your fixed height */
}
This ensures the content inside doesn’t scroll even if it overflows.
📌 Example:
<div class="scroll-locked">
<!-- Content stays fixed -->
</div>
✅ Method 4: Lock Scroll with a CSS Class (Toggle with JavaScript)
To dynamically lock and unlock scroll, you can toggle a class using JavaScript.
📌 CSS:
.no-scroll {
overflow: hidden;
}
📌 JavaScript:
document.body.classList.add('no-scroll'); // to disable
document.body.classList.remove('no-scroll'); // to enable
✅ Great for modals, popups, or mobile nav menus!
⚠️ Caution: Don’t Forget Scroll Restoration
When you disable scrolling, the scroll position is often locked. If you don’t restore it, users might be confused when reopening the page.
You can store the scroll position in JavaScript and restore it later if needed:
let scrollY = window.scrollY;
document.body.style.position = 'fixed';
document.body.style.top = `-${scrollY}px`;
// On restore
document.body.style.position = '';
document.body.style.top = '';
window.scrollTo(0, scrollY);
🧾 Summary: CSS Scroll Control
Use Case | CSS Solution |
---|---|
Disable all scroll | overflow: hidden |
Disable vertical scroll | overflow-y: hidden |
Disable horizontal scroll | overflow-x: hidden |
Lock scroll on element | overflow: hidden on div |
Dynamic toggle | Use class + JavaScript |
🧠 Conclusion
Disabling scrolling with CSS is easy and essential for building modals, overlays, and more. With overflow
properties and smart class toggling, you can create smooth, controlled experiences across all devices.
Pro Tip: Always test scroll locking on mobile devices—especially iOS Safari, which sometimes behaves differently with fixed positioning.