Avoiding Horizontal Scroll
You'll learn how to prevent unwanted horizontal scrollbars on mobile devices.
Horizontal scrollbars are one of the most frustrating user experience problems on mobile. They happen when content extends beyond the viewport width, forcing users to scroll sideways—usually by accident. Your goal is to ensure all content fits within the available screen width.
Why Horizontal Scroll Happens
Common culprits include:
- Fixed-width elements (like
width: 600pxon a 375px phone screen) - Images wider than the viewport
- Long unbreakable text or URLs
- Negative margins pushing content outside the container
- Forgetting padding when setting
width: 100%
The Core Solutions
Max-width to the rescue: Setting max-width: 100% on images and other media ensures they never exceed their container's width:
img, video {
max-width: 100%;
height: auto;
}
Think of max-width: 100% as a safety net—it says "be as wide as you want, but never wider than your container."
Control overflow: When content must extend beyond its container (like a wide data table), use overflow-x:
.table-container {
width: 100%;
overflow-x: auto;
}
This creates a scrollable area within the page instead of pushing the entire viewport wider.
Box-sizing fix: Remember that padding adds to width. Using box-sizing: border-box (which you learned earlier) ensures padding stays inside your defined widths.
Testing Tip
Always resize your browser window narrow while developing—horizontal scroll often only appears at specific breakpoints.
Key Takeaway: Prevent horizontal scroll by setting max-width: 100% on images/media and using overflow-x: auto on containers with necessarily wide content; never let elements exceed viewport width.