The Fascinating White-Space Property
June 2, 2012
Posted by on
Hidden in the train wreck that is CSS2 there is one property that is oddly useful, even ingenious: white-space. A while ago I showed how this property, applied to the body, can format a poem without a single tag in the text proper. What I did there wasn’t really different from enclosing the poem in
pre tags. But there are some other, more advanced, options as well.
Disregarding “normal” and “inherit”, the white-space property can have four values:
- pre: Just like the old HTML
pre tag, multiple whitespaces and line breaks are preserved, no line breaks will be added.
- pre-wrap: Like “pre”, everything is preserved, but lines will wrap to fit into the container, be that the screen or some HTML/CSS box.
- nowrap: Multiple white spaces are collapsed, line breaks treated as whitespace, the text will not wrap, you have to insert
<br> if you want a line break. I see little practical use for this.
- pre-line: Multiple whitespaces are collapsed, line breaks are preserved. This is where it gets interesting.
If “pre” is a good way to format a poem, then “pre-line” is a very good way to format prose, if it is in a format where paragraphs are separated with double line breaks but are internally in one line. This is a very common format for text files nowadays, it is also what you get when you do a
Ctrl-C on a web page. For texts that don’t require any markup beyond paragraphs and a single header at the top (short stories and most essays, for example), this is a very quick and easy way to convert a text file to HTML. You can even justify the text!