CSS overflow property
What is CSS Overflow?
The overflow property controls what happens to content that is too large to fit in an element's box. It determines whether content is clipped, scrollable, or visible outside the container.
Overflow Values
| Value | Description |
|---|---|
visible | Content overflows the box (default) |
hidden | Content is clipped, no scrollbar |
scroll | Content is clipped, scrollbar always visible |
auto | Scrollbar appears only when content overflows |
clip | Like hidden but prevents programmatic scrolling |
css
/* Content is clipped */
.box-hidden {
overflow: hidden;
width: 300px;
height: 200px;
}
/* Scrollbar when needed */
.box-auto {
overflow: auto;
max-height: 400px;
}
/* Always show scrollbar */
.box-scroll {
overflow: scroll;
height: 300px;
}Overflow-x and Overflow-y
You can control horizontal and vertical overflow independently:
css
.horizontal-scroll {
overflow-x: auto;
overflow-y: hidden;
white-space: nowrap;
}
.vertical-scroll {
overflow-x: hidden;
overflow-y: auto;
}Common Use Cases
1. Truncating Text with Ellipsis
css
.truncate {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 200px;
}
/* Multi-line truncation */
.truncate-multiline {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}2. Clearing Floats
css
.clearfix { overflow: auto; }3. Scroll Container
css
.chat-messages {
overflow-y: auto;
max-height: calc(100vh - 120px);
scroll-behavior: smooth;
}4. Hiding Decorative Overflow
css
.card {
overflow: hidden;
border-radius: 12px; /* Clips child content to rounded corners */
}overflow: hidden and BFC
Setting overflow: hidden (or auto, scroll) creates a Block Formatting Context (BFC), which:
- Contains floated children
- Prevents margin collapsing
- Isolates layout from surrounding elements
Important:
The overflow property is essential for creating scrollable containers, text truncation, and preventing layout overflow issues. Use auto over scroll when you want scrollbars only when needed.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.