CSS white-space Property

Here’s an interesting and little-mentioned CSS property: white-space. With it you can prevent an element’s contents from line wrapping, create pre text, even pre text that wraps when necessary.

The syntax is like this:

#mydiv {
white-space: nowrap;

The above example is fairly self-exaplanatory; it prevents the text inside the #mydiv div from wrapping. If #mydiv had a fixed width, the text would spill out of the container. However, there are practical uses for this behavior. Have you ever wanted to have an inline element (perhaps a span containing the category a blog post is assigned to) automatically move down to the next line instead of appearing across two if it were too big? Give the element nowrap.

The other major value for white-space is pre, which forces the text to appear as it was entered, leaving spaces, carriage returns and tabs intact. The counterpart is pre-wrap, which works the same way, except it will wrap the text if the containing element is too narrow. So if you use code samples in <pre> elements on a regular basis, but want to keep long lines from spilling out of their containers and creating horizontal scrollbars on your page, you can just use this:

 pre {
 white-space: pre-wrap;

Now your preformatted text will wrap down if the line is just too long.