2015-06-18

white-space: pre-line

One of the less known things in CSS is the pre-line value of the white-space property.

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

Let’s take this paragraph,

<p>This is a text which has endlines
quite often which in return makes
it easier to read ‘cause lines
don’t go to any great lengths.</p>

Normally, it would render all in one line:

This is a text which has endlines quite often which in return makes it easier to read ‘cause lines don’t go to any great lengths.

It happens like that because browser ignores most of white space: all spaces, tabs, and new lines become a single space character. But when we use white-space: pre-line, it looks like that:

This is a text which has endlines
quite often which in return makes
it easier to read ‘cause lines
don’t go to any great lengths.

It behaves much like PHP’s function nl2br(). It remains relatively unknown; in my career I had used it only on two occasions.

Further reading