Wrapping Text – Breaking Text with No Spaces into New Line

by Hiroshi on September 8, 2008

in CSS, HTML, Web Tips

Text like, a b c d e f and so on written in HTML will do fine in any browser, we all know that.

What about the following!
abcdefghijklmnopqrstuvwxyz….NoWordBreaksAndSentenceGoesOnAndOn…
The text with no spaces.

If there are no breaks in words then the sentence will proceed straight and cause horizontal scroll in web page. In blogs or in any other applications where users can comment or put some data, they can write such spam or anything that can cause your web page layout to break. We have a solution to that. Write text in pre tag and apply following CSS to it.

pre {
 overflow-x: auto; /* Use horizontal scroller if needed; for Firefox 2, not needed in Firefox 3 */
 white-space: pre-wrap; /* css-3 */
 white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */
 white-space: -pre-wrap; /* Opera 4-6 */
 white-space: -o-pre-wrap; /* Opera 7 */
 /* width: 99%; */
 word-wrap: break-word; /* Internet Explorer 5.5+ */
}

This will fix the problem and in IE it will cause line break and avoid horizontal scroll while in Mozilla Firefox it will add an inline frame and put all the data in it.

Download Example
More Detail and Examples

Related Posts

Previous post:

Next post: