CSS Overflow
When an element has too much content to fit within its specified dimensions, "overflow" occurs. The overflow property is used to control how this situation is handled.
overflow: visible;
This is the default value of overflow. Content is not clipped and renders outside the element's box.
div {
width: 200px;
height: 65px;
background-color: #eee;
border: 1px solid #ccc;
overflow: visible;
}In this case, the excess text extends outside the box, potentially covering other elements on the page, which is usually not the desired effect.
overflow: hidden;
If overflow is set to hidden, any content overflowing the container will be clipped and become invisible.
div {
overflow: hidden;
}This is useful for ensuring content doesn't break the layout, but the downside is that users cannot access the hidden content.
overflow: scroll;
overflow: scroll; clips the overflowing content but provides scrollbars so users can scroll to view all content.
A key point is that scroll will show both horizontal and vertical scrollbars, regardless of whether content overflows in both directions. This can sometimes lead to an unnecessary, disabled scrollbar appearing.
div {
overflow: scroll;
}overflow: auto;
overflow: auto; is the most commonly used and intelligent option. It adds scrollbars automatically as needed.
- If content does not overflow, no scrollbars are shown.
- If content overflows vertically, only a vertical scrollbar is shown.
- If content overflows horizontally, only a horizontal scrollbar is shown.
- If content overflows in both directions, both are shown.
div {
overflow: auto;
}This is usually the best choice when dealing with potential content overflow.
overflow-x and overflow-y
You can also control horizontal and vertical overflow behavior separately.
overflow-x: Controls horizontal (X-axis) overflow.overflow-y: Controls vertical (Y-axis) overflow.
div {
overflow-x: hidden; /* Hide horizontal scrollbar */
overflow-y: scroll; /* Always show vertical scrollbar */
}overflow is a very practical property, especially when dealing with user-generated content or in responsive design where element dimensions change, ensuring your layout remains robust.