How to prevent long words from breaking my div?

Soft hyphen

You can tell browsers where to split long words by inserting soft hyphen (­):

averyvery­longword

may be rendered as

averyverylongword

or

averyvery-
longword

A nice regular expression can ensure you won’t be inserting them unless neccessary:

/([^\s-]{5})([^\s-]{5})/ → $1­$2

Browsers and search engines are smart enough to ignore this character when searching text, and Chrome and Firefox (haven’t tested others) ignore it when copying text to clipboard.

<wbr> element

Another option is to inject <wbr>, a former IE-ism, which is now in HTML5:

averyvery<wbr>longword

Breaks with no hyphen:

averyvery
longword

You can achieve the same with zero-width space character &#8203; (or &#x200B).


FYI there’s also CSS hyphens: auto supported by latest IE, Firefox and Safari (but currently not Chrome):

div.breaking {
  hyphens: auto;
}

However that hyphenation is based on a hyphenation dictionary and it’s not guaranteed to break long words. It can make justified text prettier though.

Retro-whining solution

<table> for layout is bad, but display:table on other elements is fine. It will be as quirky (and stretchy) as old-school tables:

div.breaking {
   display: table-cell;
}

overflow and white-space: pre-wrap answers below are good too.

Leave a Comment