0
0
CssHow-ToBeginner · 3 min read

How to Use Overflow Auto in CSS for Scrollable Content

Use overflow: auto; in CSS to add scrollbars only when the content inside an element is larger than its container. This makes the container scrollable without always showing scrollbars.
📐

Syntax

The overflow property controls what happens when content is too big for its container. Using overflow: auto; means scrollbars appear only if needed.

  • overflow: The CSS property to control overflow behavior.
  • auto: Adds scrollbars only when content overflows.
css
selector {
  overflow: auto;
}
💻

Example

This example shows a box with fixed width and height. When the text inside is too long, scrollbars appear automatically.

css
html, body {
  height: 100%;
  margin: 0;
  font-family: Arial, sans-serif;
}
.container {
  width: 300px;
  height: 150px;
  border: 2px solid #333;
  padding: 10px;
  overflow: auto;
  background-color: #f0f0f0;
  box-sizing: border-box;
}
Output
<div class="container">This is a box with fixed size. When the content inside is longer than the box, scrollbars appear automatically so you can scroll to see all the text. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
⚠️

Common Pitfalls

People often forget to set a fixed size on the container, so overflow: auto; has no effect because the container grows with content. Also, using overflow: auto; on inline elements won't work; it must be on block or inline-block elements.

Wrong example: No fixed height, so no scrollbar.

css
.no-scroll {
  border: 1px solid red;
  overflow: auto;
  /* No height or width set */
}

.correct-scroll {
  border: 1px solid green;
  overflow: auto;
  height: 100px;
  width: 200px;
}
Output
<div class="no-scroll">This container has no fixed size, so no scrollbar appears even if content is long. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div><div class="correct-scroll">This container has fixed size and overflow auto, so scrollbars appear when needed. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
📊

Quick Reference

  • overflow: auto; - Scrollbars appear only if content is bigger than container.
  • Works only on block or inline-block elements with fixed size.
  • Use with width and height set for scrollbars to show.
  • Good for making scrollable boxes without always showing scrollbars.

Key Takeaways

Use overflow: auto; to add scrollbars only when content overflows its container.
Set fixed width and height on the container for scrollbars to appear.
Apply overflow: auto; on block or inline-block elements, not inline elements.
It helps keep UI clean by showing scrollbars only when needed.
Remember scrollbars appear vertically, horizontally, or both depending on content size.