Pre-formatting HTML Text

Web browsers are designed to be very fault tolerant. For this and other reasons they typically ignore sequences of empty spaces, multiple empty <p> tags and all carriage return characters. This can turn out to be very inconvenient when one wants to accurately control the layout of displayed text. For instance, on this site we often show snippets of code laid out to improve readability. We use the <pre>..</pre> tag pair accomplish this.

pre defines a pre-formatted text block. Browsers are programmed to display all spaces and honor all carriage return characters that they encounter within the block. Pre-formatted elements have a small number of useful attributes:

The problem with issuing a pre command to a browser is that it blocks all word wrapping. Given that the user can alter the size of text displayed by the browser - all browsers allow this with Opera offering the best functionality - it is not possible to code in line breaks into your pre-formatted text in such a way as to ensure that text always wraps round correctly to fit inside the clientwidth of the containing element. To avoid this problem the pre element should be subjected to the following bare minimum CSS styling

white-space:pre-wrap;
white-space:-moz-pre-wrap;
white-space:-pre-wrap;
white-space:-o-pre-wrap;
word-wrap:break-word;

In a perfect world only the first line - which defines the CSS 3 standard attribute setting - would be necessary. In practice it is best to include all five lines to allow for the vagaries of all browsers. It goes without saying that you are at liberty to assign other CSS attributes such as font color, style etc.

Jump To...

Colophon