Overflow-Wrap, Word Wrap and Hyphens Where Possible

For responsive design we usually need to prevent long URLs and words from breaking layout on narrow screens. Here’s the CSS to break long words that fly out of a small screen layout.

-ms-word-break: break-all;
word-break: break-all;

/* Non-standard for webkit */
word-break: break-word;

/* Add hyphens based on language */
-webkit-hyphens: auto;
-moz-hyphens: auto;
-ms-hyphens: auto;
hyphens: auto;

Hyphens Are Dependent on Language

It’s very important to add lang="en" to html element. Otherwise hyphens wouldn’t appear. They depend on language libraries in browser, so you may test them with your own language too.

Word Wrap and Its Difference with Word Break

There is also another CSS code word-wrap: break-word; which is better supported in browsers. It wraps words only when some width of a container specified. More similar to white-space for words. I.e. with word-break, text will continue inline and long words will go inline until they have to break to new line. With word-wrap, words will go to a next line and only broken when run out of space. Also word-wrap will not break words inside tables running out of layout, but word-break would do.

Beware that word-break can break words in odd places, so I use to insert such code with media queries for small screens only.

Update for 2017: overflow-wrap

Property word-wrap has been renamed to overflow-wrap now.

I found it is now better to use the following code, as it doesn’t break words in a wrong place, where possible. Browser support is great. So no media queries required anymore. Also hyphens are added in more browsers, than with previous code.

 overflow-wrap: break-word;
word-wrap: break-word;
-webkit-hyphens: auto;
-ms-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;

 

 

Share:
This entry was posted in CSS CheatSheets and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *