CSS word-wrap (or overflow-wrap) property
The word-wrap
(or overflow-wrap
) Property in CSS
The word-wrap
property, which is now more commonly referred to as overflow-wrap
, is used to control how text wraps within an element. It specifically addresses how to handle long words or unbreakable text that might otherwise overflow the container. This property is crucial for ensuring text content remains within the boundaries of its container, especially in responsive designs.
Values of overflow-wrap
normal
- Description: The default value. Words are only broken at allowed break points (such as spaces). Long words or URLs that exceed the container width may overflow.
- Example:
.normal-wrap { overflow-wrap: normal; /* Text breaks only at allowed break points */ }
break-word
- Description: Breaks long words or unbreakable text to fit within the container if necessary. This ensures that even very long words will be broken up to prevent overflow.
- Example:
.break-word { overflow-wrap: break-word; /* Breaks long words to fit within the container */ }
Differences Between word-wrap
and overflow-wrap
word-wrap
: The older name for the property, which is still widely used. It serves the same function asoverflow-wrap
.overflow-wrap
: The newer, standardized name for the property. It is recommended to useoverflow-wrap
for consistency and future-proofing.
Examples
Normal Wrapping
.normal-wrap { overflow-wrap: normal; /* Default behavior, long words may overflow */ }
Breaking Long Words
.break-word { overflow-wrap: break-word; /* Ensures long words are broken to fit within the container */ }
Explanation
normal
: With this setting, text will break only at natural break points, such as spaces or hyphens. This means that very long words or URLs might overflow the container if they do not contain any natural break points.break-word
: This setting forces the browser to break long words or URLs at any point necessary to prevent overflow, ensuring that the text fits within the container. This can be particularly useful for handling long strings of text in responsive designs.
Use Cases
- Responsive Design: Use
break-word
to handle long text in responsive layouts, ensuring that content does not overflow the container on smaller screens. - User-Generated Content: Apply
break-word
to prevent issues with unbreakable text, such as URLs or long strings of data, that might be included in user-generated content. - Design Consistency: Use
normal
where text formatting and break points are controlled and predictable, allowing for design consistency.