CSS: useful white-space values

The CSS white-space property has two special values that turn out to be very useful when dealing with pre-formatted text, especially when contained within a pre element. This HTML element has white-space: pre as its default CSS style and, as you may have guessed viewing some blogs, sometimes it's not the ideal choice. The problem with the pre value is that long lines are not contained nor wrapped in any way, so your text will often overflow its container. Fortunately, the pre-wrap and pre-line values of the white-space property fix this problem.

The former value works with the entire text, while the latter on single lines. The final result is having your text always contained within its container, without any possible overflow:

pre {
 font: 1em "Courier New", Courier, monospace;
 background: #ffc;
}

.pre-wrap {
 white-space: pre-wrap;
}

.pre-line {
 white-space: pre-line;
}

Since both values work on spaces inside text, you will probably notice that when you use these values all your indentations are removed. This is the normal behavior for these values. A good solution is to balance these properties with the overflow property or use both values on the parent element. You can see a test below.

Test

Live test

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.