🌱BeginnerCSS Layout Basics
CSS Overflow
Control what happens when content is too large for its container using overflow: visible, hidden, scroll, and auto.
Overview
The `overflow` property controls what happens when an element's content is larger than its box. By default, content simply spills outside the element (overflow: visible). You can clip it, add scrollbars, or let the browser decide.
The values:
- `visible` (default) content overflows the box without clipping
- `hidden` content is clipped; overflow is not visible
- `scroll` scrollbars always appear (even if not needed)
- `auto` scrollbars appear only when needed
- `clip` clips like hidden but disables programmatic scrolling
You can control axes independently: `overflow-x` (horizontal) and `overflow-y` (vertical).
Overflow: hidden is also commonly used as a technique: it creates a new Block Formatting Context (BFC), which contains floats and prevents margin collapse.
Key Points
- •overflow: visible (default) content spills outside the box
- •overflow: hidden clips content at the element boundary
- •overflow: auto adds scrollbar only when content overflows (preferred over scroll)
- •overflow: scroll always shows scrollbars even when not needed
- •overflow-x and overflow-y control each axis independently
- •overflow: hidden on a parent contains floated children (BFC trick)
Examples
Common overflow patterns
/* Scrollable code block */
pre {
overflow: auto; /* scrollbar appears only if code is too wide */
max-height: 300px; /* vertical scroll when content is tall */
}
/* Image container that clips overflow */
.thumbnail {
width: 200px;
height: 150px;
overflow: hidden; /* clips the image to the box */
}
/* Scrollable list */
.dropdown-list {
max-height: 200px;
overflow-y: auto; /* vertical scroll, no horizontal */
}overflow: hidden as a float container
/* Contains floated children without clearfix */
.card {
overflow: hidden; /* creates BFC, contains float children */
}overflow: hidden is a common alternative to the clearfix hack for containing floats.
Horizontal scroll for overflow tables or code
.table-wrapper {
overflow-x: auto; /* horizontal scroll if table is too wide */
overflow-y: visible; /* no vertical clip */
-webkit-overflow-scrolling: touch; /* smooth on iOS */
}Common Mistakes
- Using overflow: scroll when overflow: auto is cleaner scroll always shows scrollbars even when unnecessary
- Forgetting to set a height or max-height when using overflow-y: auto without a height the element just grows
- Using overflow: hidden on a tooltip container and then wondering why the tooltip is clipped
Note
For scrollable areas, always prefer overflow: auto over overflow: scroll. auto only shows a scrollbar when needed, scroll always shows it (which looks odd when the content fits).
Exercises
Write CSS to style the HTML scaffold. The preview updates live — when it looks right, mark as done.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4