How to Prevent Text Overflow in CSS: Simple Fixes
overflow: hidden; or overflow: auto; on the container, combined with white-space: nowrap; and text-overflow: ellipsis; to neatly cut off and show dots when text is too long. These properties keep text inside its box and show a clear visual cue if it doesn't fit.Why This Happens
Text overflow happens when the text inside a container is longer than the container's width. The container does not automatically cut off or wrap the text, so it spills outside, breaking the layout or hiding behind other elements.
<div style="width: 150px; border: 1px solid black;">
This is a very long text that will overflow the container and cause layout issues.
</div>The Fix
To fix overflow, set the container's overflow to hidden or auto. Use white-space: nowrap; to keep text on one line, and text-overflow: ellipsis; to show three dots (...) when text is cut off. This keeps text inside the box and visually neat.
<div style="width: 150px; border: 1px solid black; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">
This is a very long text that will overflow the container and cause layout issues.
</div>Prevention
Always set a fixed or max width on containers that hold text. Use overflow, white-space, and text-overflow together to control text display. Test your design on different screen sizes to ensure text fits well. Use responsive units like rem or percentages for widths.
Lint your CSS or use style guides to enforce these rules in your projects.
Related Errors
Other common text display issues include:
- Text wrapping unexpectedly: Fix by setting
white-space: normal;or removingnowrap. - Container height too small: Use
min-heightor allow wrapping. - Invisible overflow: Happens when
overflow: hidden;cuts off important content; consideroverflow: auto;with scrollbars.