0
0
CssHow-ToBeginner · 3 min read

How to Use overflow-x and overflow-y in CSS for Scroll Control

Use 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.
css
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.

css
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;
}
Output
<div class="container"><div class="item">Box 1</div><div class="item">Box 2</div><div class="item">Box 3</div></div>
⚠️

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.

css
/* 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

ValueMeaning
visibleContent is not clipped, may overflow outside box
hiddenContent is clipped, no scrollbars shown
scrollScrollbars always visible, content can be scrolled
autoScrollbars shown only if content overflows

Key Takeaways

Use overflow-x to control horizontal overflow and overflow-y for vertical overflow separately.
Set fixed width or height on containers to enable scrollbars when needed.
Use 'auto' to show scrollbars only when content is too big.
Avoid clipping content unintentionally with 'hidden' unless you want to hide overflow.
Test scroll behavior on different screen sizes for good user experience.