pre element
If you don't know what an element is or how you must use it, I recommend you read the "HTML tags and attributes" tutorial that you can find in the HTML tutorials section.
Table of contents
Description
The pre
element represents a block of preformatted text where, in contrast with other elements, continuos spaces and line breaks are respected. Also, browsers use fixed-pitch fonts to represent the text in this element, which means that all characters will have the same width.
The pre
element is commonly used to display computer code, plain text or ascii art. In some cases, it's accompanied by other elements like code
, samp
or kbd
.
Examples
In the following example there's a paragraph followed by a pre
block, both intentionally with the same content, so you can see the difference between them and what's particular about the pre
block.
<p>The things you'll need are listed here:
- A lantern.
- A matches box.
- A sharp knife.
</p>
<pre>The things you'll need are listed here:
- A lantern.
- A matches box.
- A sharp knife.
</pre>
The things you'll need are listed here: - A lantern. - A matches box. - A sharp knife.
The things you'll need are listed here: - A lantern. - A matches box. - A sharp knife.
An important thing to note here is that the browser strips all repeated whitespace and linebreaks for the p
element (and all other elements except pre
).
Now, in the second example, we'll see how the pre
element is combined with code
to display a piece of computer program.
<p>The function goes as follows:</p>
<pre><code>function sayHello() {
console.log('Hello!');
alert('Hello!');
}</code></pre>
The function goes as follows:
function sayHello() {
console.log('Hello!');
alert('Hello!');
}
Note how in this example, pre
is containing code
and not the other way around. This is because code
is unable to contain flow elements like pre
. The same reasoning applies to other elements like samp
or kbd
.
Attributes
Specific attributes
width
A number of characters to use as the width of the block.
This attribute has become obsolete in HTML5 because of its presentational nature. Authors should drop its use in favor of style sheets.
Example
<pre width="10">bool sayHello(int times);</pre>
Global attributes
For information about global attributes refer to this list of global attributes in HTML5.
Events
Global events
For information about global events refer to this list of global events in HTML5.