CSS Overflow
Manage content that extends beyond an element's box.
CSS overflow happens when content is too large to fit inside an element. For example, text may extend outside a box when the box has a fixed height.
.box {
width: 250px;
height: 100px;
border: 2px solid blue;
}The overflow property controls what happens to the extra content.
overflow: visible
visible is the default value. Extra content remains visible even if it extends outside the element.
.box {
height: 100px;
overflow: visible;
}Important points:
- The overflowing content is not removed.
- It may cover nearby elements.
- No scrollbar is added.
overflow: hidden
The hidden value clips any content that extends outside the element.
.card {
width: 250px;
height: 100px;
overflow: hidden;
}Use it when:
- Extra content should not be displayed.
- An image must remain inside a rounded container.
- A decorative element extends beyond its parent.
Hidden content may become inaccessible, so avoid using it for important information.
overflow: scroll
The scroll value clips extra content and adds scrollbars.
.article {
width: 300px;
height: 150px;
overflow: scroll;
}Users can scroll to view the remaining content. Some browsers may display scrollbars even when the content already fits.
overflow: auto
The auto value adds scrollbars only when they are needed.
.comments {
max-height: 200px;
overflow: auto;
}This is useful for:
- Comment sections
- Code examples
- Dropdown lists
- Tables inside small containers
- Modal content
In many situations, auto is more practical than scroll.
Controlling Horizontal and Vertical Overflow
The overflow-x and overflow-y properties control each direction separately.
.code-box {
overflow-x: auto;
overflow-y: hidden;
}- overflow-x controls left and right overflow.
- overflow-y controls top and bottom overflow.
For example, a wide table can scroll horizontally:
.table-wrapper {
overflow-x: auto;
}This helps prevent the table from breaking a mobile layout.
Handling Overflowing Text
The text-overflow property controls clipped inline text. It is commonly used to display an ellipsis.
.product-name {
width: 200px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}If the product name is too long, the browser displays ....
The three properties work together:
- white-space: nowrap keeps the text on one line.
- overflow: hidden clips the extra text.
- text-overflow: ellipsis displays the ellipsis.