Skip to: content, navigation

by Ian Lloyd

pre (HTML element)

Spec
Depr. Empty Version
No No HTML 2
Browser support full matrix
IE5.5+ FF1+ Saf1.3+ Op9.2+
Full Full Full Full

Example

A snippet of HTML on a reference web site, in this case using the pre and code elements to markup some code:
<pre><code>//Do a bit of code debugging     ||-- Check Array vals
document.write ("&lt;ul&gt;");
for (i=1;i&lt;array.length;i++)
 {
 str += "&lt;li&gt;Value of array " + i + " is: " +array[i] + "&lt;/li&gt;";
 }
document.write(str);
document.write ("&lt;/ul&gt;");
</code></pre>
Type
block-level element
Contains
inline elements only
Contained by
block-level elements

Description

The pre element is used to preserve important whitespace and carriage returns in source markup that HTML or XHTML would otherwise ignore. By default, only the first space is honored; subsequent spaces—unless specified using the &nbsp; entity—aren’t rendered by browsers. The pre element is most frequently used in conjunction with the code element to render code examples in which the presence of spaces and/or carriage returns may make a crucial difference as to whether the code will work or not when it is copied and pasted elsewhere.

The example presented above would appear on screen as shown in Figure 1. Note the spacing before the ||—Check Array vals section, as well as the fact that each line is output on a new line without the need for a br element.

Figure 1. Displaying some code using pre Example of pre element

In this example, JavaScript is being used to write out HTML, which is then rendered on screen. Thus, in the source code, the opening and closing ul and li tags are written as &lt;ul&gt;&lt;/ul&gt;, and &lt;li&gt;&lt;/li&gt; respectively, so that the browser displays them on screen rather than attempting to interpret them and create new list items.

Use This For …

Use pre for content whose whitespace has semantic meaning. If you want to retain whitespace for visual purposes, but those spaces don’t actually have any semantic meaning, use the "white-space" CSS property instead.

Compatibility

IE5.5Full
6.0Full
7.0Full
Firefox1.0Full
1.5Full
2.0Full
Safari1.3Full
2.0Full
3.0Full
Opera9.2Full
9.5Full

The pre element enjoys good browser support, with all the major browsers rendering it in a fixed-width font—usually Courier.

Related Reading

User-contributed notes

There are no comments yet.

Add a note

To post a note on this topic, please log in with your SitePoint username and password. If you don't have an account yet, you can create a new account for free.

Related Products

The Principles of Beautiful Web Design

Best Seller!

You don’t need to go to Art School to design great looking web sites!

Book Cover: The Principles of Beautiful Web Design

Download the FREE sample chapters