When content is too large for its container, you need to decide what happens. Does the
content overflow and get hidden? Does scrollbars appear? The overflow property
gives you control over this behavior. It is one of those properties that you will use
constantly once you know it exists.
The Main Values
overflow has several values: visible (the default), hidden,
scroll, and auto. Each one handles overflow differently.
/* Default: content spills out */
.visible {
overflow: visible;
}
/* Content is clipped, no scrollbar */
.hidden {
overflow: hidden;
}
/* Always shows scrollbars */
.scroll {
overflow: scroll;
}
/* Scrollbars only when needed */
.auto {
overflow: auto;
}
visible lets content overflow beyond the box. hidden clips it
cleanly. scroll always shows scrollbars. auto shows scrollbars
only when content overflows — usually the best choice.
Axis-Specific Overflow
You can control overflow on each axis independently with overflow-x and
overflow-y. This is useful when you want horizontal scrolling but no
vertical scrolling, or vice versa.
.horizontal-scroll {
overflow-x: auto;
overflow-y: hidden;
}
.vertical-only {
overflow-x: hidden;
overflow-y: auto;
}
A common pattern is a sidebar that scrolls vertically but not horizontally, while the main content scrolls in both directions. Axis-specific overflow makes this possible.
Creating Scrollable Containers
The most common use is creating scrollable containers with a fixed height. Set a max
height on the container and overflow: auto, and the container becomes
scrollable when content exceeds that height.
.chat-window {
max-height: 400px;
overflow-y: auto;
border: 1px solid #ddd;
}
This creates a chat-style window where messages scroll within a fixed area. The scrollbar appears only when there are enough messages to exceed the max height.