How to wrap long lines without spaces in HTML?

If a user types in a long line without any spaces or white space, it will break formating by going wider than the current element. Something like:

HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA.............................................................................................................................................

I've tried just using wordwrap() in PHP, but the problem with that is if there is a link or some other valid HTML, it breaks.

There seems to be a few options in CSS, but none of them work in all browsers. See word-wrap in IE.

How do you solve this problem?


in CSS3:

word-wrap:break-word

I was trying to solve the same problem and I found de solution here:

http://perishablepress.com/press/2010/06/01/wrapping-content/

Solution: adding to the container the following CSS properties

div {
    white-space: pre;           /* CSS 2.0 */
    white-space: pre-wrap;      /* CSS 2.1 */
    white-space: pre-line;      /* CSS 3.0 */
    white-space: -pre-wrap;     /* Opera 4-6 */
    white-space: -o-pre-wrap;   /* Opera 7 */
    white-space: -moz-pre-wrap; /* Mozilla */
    white-space: -hp-pre-wrap;  /* HP Printers */
    word-wrap: break-word;      /* IE 5+ */
}

The idea is using them all so you get better cross-browser compatibility

Hope this helps


I like to use the overflow: auto CSS property/value pairing. This will render the parent object the way you'd expect it to appear. If the text within the parent is too wide, scrollbars appear within the object itself. This will keep the structure the way you want it to look and provide the viewer with the ability to scroll over to see more.

Edit: the nice thing about overflow: auto compared to overflow: scroll is that with auto, the scrollbars will only appear when overflowing content exists. With scroll, the scrollbars are always visible.


I haven't personally used it, but Hyphenator looks promising.

Also see related (possibly duplicate) questions:

  • word wrap in css / js
  • Who has solved the long-word-breaks-my-div problem? (hint: not stackoverflow)