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
classattribute is discussed here. One can locally alter some aspects of the assigned style by defining an inline style using the codestyle="color:...". Needless to say, only those style attributes that require altering/adding need to be specified. - The
idattribute is discussed here. - The events available across all three browsers - Firefox, Opera and IE - are discussed here.
- The
styleattribute is used to assign inline CSS styling information to the element. The specification takes the formstyle="color:...". Inline styling should be used sparingly to temporarily override CSS attributes inherited from aclassspecification.
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.