How to wrap long lines without spaces in HTML?

Viewed 83957

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?

14 Answers

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 would put the post in a div that would have a fixed width setting overflow to scroll (or to hide completely depending on the content).

so like:

#post{
    width: 500px;
    overflow: scroll;
}

But that's just me.

EDIT: As cLFlaVA points out... it is better to use auto then scroll. I do agree with him.

I dodge the problem by not having my right sidebar fixed like that :P

Here's what I do in ASP.NET:

  1. Split the text field on spaces to get all the words
  2. Iterate the words looking for words that are longer than a certain amount
  3. Insert every x characters (e.g. every 25 characters.)

I looked at other CSS based ways of doing this, but didn't find anything that worked cross-browser.

I have posted a solution which uses JavaScript and a simple Regular Expression to break long word so that it can be wrapped without breaking your website layout.

Wrap long lines using CSS and JavaScript

Related