CSS word-break and word-wrap

Published:
Tags:
css html
Reading time:
About 2 min

Finding a cross-browser CSS solution to force breaks in long words inside of table-cells is not an easy task. My issue was specifically with email addresses formatted like [email protected]. The snag is that support is decent inside of block-level elements like divs, but only hacks seem to exist for table cells.

The widely supported white-space will instruct the browser to wrap on normal wrapping characters, but the browsers will not break a word. There are two newer CSS properties to try: word-wrap and word-break.

word-break:break-all will force a break anywhere but ignores spaces. It works well if you know your table cell will only contain a single term or word, and you don’t care about wrapping on commas, hyphens, or spaces.

word-wrap:break-word will honor commas, hyphens, and spaces to wrap first and then will force a break in the middle of words when needed. The catch is it only works cross-browser on block-level elements and not on table cells. Also a width or max-width must be specified.

One promising hack sets a table to be table-layout:fixed but this did not work with the jQuery datatables plugin.

So here is my cross browser solution, tested in Chrome, Firefox, and IE9. It unfortunately requires wrapping your td contents inside of a div. But it does work with the jQuery datatables plugin.


CSS:
/* forces wraps in middle of words when necessary */
div.force-wrap {
  white-space: normal;
  word-wrap: break-word;
}
td.email,
td.email div.force-wrap {
  width: 30em;
}

Html:
<table><tbody>
<tr>
  <td class="”email”">
<div class="”forcewrap”">
[email protected], [email protected]
</div>
</td></tr>
</tbody></table>



Additional References

https://bugs.webkit.org/show_bug.cgi?id=43917
http://blog.kenneth.io/blog/2012/03/04/word-wrapping-hypernation-using-css/
http://petesbloggerama.blogspot.com/2007/02/firefox-ie-word-wrap-word-break-tables.html