Forcing Line Breaks for Long Words With CSS

Posted on May 26, 2011 in CSS | 0 comments

Sometimes, especially when you are showing a long URL in a floating div, it will sneak its way out of the div and spill across the page, across the rest of your layout instead of neatly having a line break where it belongs. It doesn’t word wrap because it’s only “one word”–no space.

There are various solutions, such as these CSS tweaks.

You could manually add a <br /> tag, which is often the quickest and dirtiest way, but this only works if you are manually editing the content–and only if the user doesn’t change the font size or something to make your static line break no longer appropriate.

Another approach is to create a form style textbox and put the content in there. In some situations, such as giving code samples, this may be appropriate. Others, not so much.

Sometimes people even write server-side scripts to track down those long lines and add in line breaks dynamically… of course, they have to make guesses about how long is “too long,” and running those adds more processing and complexity.

The best solution I have found to the issue of fixing word wrapping with CSS is this blog on css code to wrap long lines. It suggests adding this CSS:

pre {
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 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}

Naturally, it doesn’t have to be the <pre> tag. It could as easily be <code> or a certain class of <p> or anything else. But this should take care of your word wrapping issues quickly and easily.

Submit a Comment

Manage your comment subscriptions