35. Handling Overflowing Text (white-space, overflow)
Sometimes text content exceeds the bounds of its container. CSS offers tools to manage this overflow gracefully.
1. Controlling Wrapping (white-space)
This property dictates how whitespace inside an element is handled and if content should wrap.
| Value | Description |
|---|---|
normal (default) | Whitespace collapses, and text wraps when necessary. |
nowrap | Text will never wrap, causing it to overflow the container horizontally. |
pre | Preserves both whitespace and line breaks (similar to the HTML <pre> tag). |
css .no-wrap { white-space: nowrap; /* Forces content onto a single line */ }
2. Controlling Overflow (overflow)
When content (text or images) exceeds the element's box, the overflow property controls what happens.
| Value | Description |
|---|---|
visible (default) | Overflowing content is displayed outside the box. |
hidden | Overflowing content is clipped and hidden. |
scroll | Always adds scrollbars (horizontal and vertical), even if not needed. |
auto | Adds scrollbars only if the content overflows (best practice). |
css .container-clip { height: 200px; overflow: hidden; /* Cuts off content that goes beyond 200px height */ }
.scroll-box { width: 300px; height: 150px; overflow: auto; /* Scrollbars appear if content needs them */ }
Note: You can control overflow directionally using overflow-x (horizontal) and overflow-y (vertical).