How to Use overflow-x and overflow-y in CSS for Scroll Control
overflow-x to control horizontal overflow and overflow-y to control vertical overflow of content in an element. These properties accept values like visible, hidden, scroll, and auto to manage how extra content is shown or clipped.Syntax
The overflow-x and overflow-y properties control how content that is too wide or too tall for its container is handled. Each can have these values:
visible: Content is not clipped and may overflow.hidden: Content is clipped and not visible outside the box.scroll: Scrollbars always appear to allow scrolling.auto: Scrollbars appear only if needed.
selector {
overflow-x: visible | hidden | scroll | auto;
overflow-y: visible | hidden | scroll | auto;
}Example
This example shows a box with fixed width and height. The overflow-x is set to scroll so a horizontal scrollbar appears if content is wider. The overflow-y is set to hidden so vertical overflow is clipped and no scrollbar appears.
html, body {
height: 100%;
margin: 0;
}
.container {
width: 300px;
height: 100px;
border: 2px solid #333;
overflow-x: scroll;
overflow-y: hidden;
white-space: nowrap;
}
.item {
display: inline-block;
width: 150px;
height: 120px;
background-color: #8ac;
margin-right: 10px;
color: white;
font-weight: bold;
text-align: center;
line-height: 120px;
user-select: none;
}Common Pitfalls
One common mistake is setting overflow-x or overflow-y without a fixed size on the container, so scrollbars never appear because the container expands to fit content. Another is using overflow: hidden unintentionally, which clips content and hides it without scrollbars, confusing users.
Also, setting overflow-x and overflow-y to conflicting values can cause unexpected scroll behavior.
/* Wrong: No fixed height, so vertical overflow won't scroll */ .container { width: 300px; overflow-y: scroll; } /* Right: Fixed height allows vertical scrolling */ .container { width: 300px; height: 100px; overflow-y: scroll; }
Quick Reference
| Value | Meaning |
|---|---|
| visible | Content is not clipped, may overflow outside box |
| hidden | Content is clipped, no scrollbars shown |
| scroll | Scrollbars always visible, content can be scrolled |
| auto | Scrollbars shown only if content overflows |