CSS Overflow Property Tutorial
The CSS overflow property controls what happens when content inside an element exceeds the available space.
Sometimes text, images, or other elements become larger than their container. In such cases, overflow rules determine how the extra content is handled.
The overflow property helps developers control layout behavior and prevent design issues caused by excessive content.
CSS provides several overflow options including visible, hidden, scroll, and auto.
1. Overflow Visible
The visible value allows content to overflow outside the container.
This is the default behavior for most elements.
.box {
width: 200px;
height: 100px;
overflow: visible;
}
2. Overflow Hidden
The hidden value hides any content that exceeds the container boundaries.
Extra content will not be visible to the user.
.box {
width: 200px;
height: 100px;
overflow: hidden;
}
3. Overflow Scroll
The scroll value adds scrollbars to the container.
Users can scroll to view the hidden content.
.box {
width: 200px;
height: 100px;
overflow: scroll;
}
4. Overflow Auto
The auto value automatically adds scrollbars only when necessary.
If the content fits inside the container, no scrollbar is shown.
.box {
width: 200px;
height: 100px;
overflow: auto;
}
Overflow X and Y
CSS also allows separate control for horizontal and vertical overflow.
- overflow-x controls horizontal overflow
- overflow-y controls vertical overflow
.box {
overflow-x: hidden;
overflow-y: scroll;
}
Complete Overflow Example
.container {
width: 300px;
height: 150px;
border: 1px solid black;
overflow: auto;
}
Best Practices
- Use overflow hidden to prevent layout breaking.
- Use overflow auto for scrollable content containers.
- Avoid unnecessary scrollbars.
- Test overflow behavior on different screen sizes.
Conclusion
The CSS overflow property helps manage content that exceeds container boundaries.
By using visible, hidden, scroll, and auto values, developers can control how extra content is handled.
Understanding overflow behavior is important for building clean and user-friendly layouts.
Codecrown