This reference is built into PageRIJ — a live HTML, CSS & SVG authoring and learning environment.

HTML <pre> element

The <pre> element represents preformatted text. By default, spaces, tabs, and line breaks are preserved, and the text uses a monospace font. CSS can change its font and whitespace behaviour.

This matters because normal HTML collapses runs of whitespace. Several spaces usually become one space, and line breaks in the source usually do not create line breaks on the page. The <pre> element changes that behaviour for text where the layout itself is meaningful.

Common uses include code blocks, command-line examples, plain-text diagrams, poetry, logs, and copied output where line structure matters. Long lines do not wrap by default. CSS can allow wrapping with white-space: pre-wrap, as on this page, or provide horizontal scrolling with overflow-x: auto.

When the preformatted text is code, <pre> is commonly combined with <code>. The <pre> element preserves the shape; the <code> element says what kind of text it is.

One small trap is the first newline after the opening <pre> tag. In HTML parsing, a newline immediately following the opening tag is stripped. A newline after a nested opening <code> tag is not immediately after <pre>, so it is preserved. The example below starts its text directly after <code> to avoid an extra blank line.

The <pre> element should not be used merely to push text into place. If the aim is page layout, CSS is the proper tool. If the spacing is part of the text itself, <pre> is the right element.

Preformatted text is still parsed as HTML. Use &lt; to show a literal less-than sign and &amp; when an ampersand must be shown literally, such as in a character reference. For a text diagram whose meaning depends on its spacing, also provide an explanation that makes sense when read aloud.

Attributes: GLOBALS.

Typical layout:
<pre><code>p {
  color: tomato;
}</code></pre>
Visual representation:
p {
  color: tomato;
}