Is there a way to word-wrap long words in a div?
To enable automatic line-breaking in a div
, the overflow-wrap: break-word;
CSS rule is your friend. This ensures that stubbornly long words won't overflow their container. Here's how to employ it:
Add this to your div
's style, and long words will respect the boundaries of your layout.
Keeping it consistent across browsers
Attaining the blissful state of cross-browser compatibility requires more than just overflow-wrap
. Consider word-break: break-all;
which insists on a hard break at the very edge of the container, humanity of the word notwithstanding.
Also, for maintaining integrity of white-space, especially with those legacy browsers, -moz-pre-wrap
(for archaic versions of Firefox) or -pre-wrap
might be necessary. Here's the complete recipe for a cross-browser word-wrap:
Dealing with white space and uncanny wrapping
When dealing with pre
-formatted text or strings notable for significant white-space, the white-space: pre-wrap;
comes into play. Preserving formatting and indentation whilst allowing for normal word wrapping is its specialty:
Do cross-check in different browsers for consistent wrapping performance. With lengthy text, its impact on usability and readability shouldn't be overlooked. Note: word-wrap
was overflow-wrap
before CSS3, so ensure you match the property with its timeline correctly.
Marrying server and client-side tactics for wrapping
In some cases, specifically with content birthed dynamically or from user input sourcing long unbroken strings, HTML/CSS-only wrapping may be a little underpowered. Here, gently introducing soft-hyphens (­
) or wrap opportunities on the server side can help wrap text before the browser even gets its hands on the content.
For exceptional requirements or precise control, JavaScript could come in handy to insert breaks or dynamically alter styles.
Styling for optimal wrapping
A div's padding and width do influence word wrapping. Padding shrinks the effective available content width, potentially triggering more breaks. Here's a handy piece of illustrative CSS:
When adjusting font-size within wrapped elements, pay attention to visual harmony. Prevent awkwardly broken words from hogging the limelight in your layout.
Was this article helpful?