CSS `word-wrap`: Controlling Long Word Handling and Text Overflow
Learn how to manage long words and prevent horizontal scrolling in your CSS layouts using the `word-wrap` property. This tutorial explains the `normal` and `break-word` values, demonstrating how to control whether long words are broken to fit within their container or allowed to overflow, creating more user-friendly and responsive text rendering.
Controlling Word Wrapping with CSS `word-wrap`
Understanding `word-wrap`
The CSS `word-wrap` property controls how long words are handled when they reach the end of a line within a container. It determines whether the browser should break the word to prevent overflow or if it should allow the word to extend beyond the container's boundary, potentially causing a horizontal scrollbar. This property is particularly helpful for long words that might not fit within the available space.
`word-wrap` Property Values
The `word-wrap` property has these key values:
normal
(default): Words are broken only at allowable break points (like spaces or hyphens). Long words that don't have suitable breakpoints will overflow their container.break-word
: If a word is too long to fit on a line, it's broken to prevent overflow. The browser will break the word at any character rather than trying to find an appropriate break point.initial
: Resets the property to its default value (normal
).inherit
: Inherits the value from its parent element.
Example: `word-wrap: break-word;`
This example shows how `word-wrap: break-word;` handles a very long word within a container with a limited width. You'd need an HTML element (like a paragraph) containing the long word to view this. The CSS `word-wrap` property would be applied to the containing element.
CSS Code
p {
width: 150px; /* Example width */
word-wrap: break-word;
}
Conclusion
The `word-wrap` property is an important tool for controlling how text handles overflow. By setting it to `break-word`, you can prevent long words from causing horizontal scrolling, ensuring that the text flows correctly within its boundaries. Remember that the choice between `normal` and `break-word` depends on your specific layout requirements.