<pre>

Preformatted text: it preserves spaces, tabs, and line breaks exactly as they appear in the code.

Display
block
Closing tag
Required
Permitted content
Phrasing content
On this page

Example

#
HTML
<pre><code>function greet(name) {
  return 'Hello, ' + name + '!';
}

console.log(greet('Ola'));</code></pre>
Preview

Definition and usage

#

Normally, the browser collapses several spaces into one and ignores line breaks in the HTML code. The <pre> element turns off that behavior: the text displays exactly as it looks in the code, with every space, tab, and new line. By default it uses a monospace font.

Most often it holds code listings, terminal command output, directory trees, or ASCII art. Put program code in the pair <pre><code>…</code></pre>: <pre> takes care of the formatting, and <code> says that this is code.

The < and & characters still carry special meaning inside it, so write them as &lt; and &amp;. Long lines don’t wrap on their own and can stick out past the container, which is why overflow-x: auto is usually added. The parser skips a single line break right after the opening tag, so you can safely start the content on a new line.

Syntax

#
Syntax
<pre>
text   that   will   keep
    all the spacing
</pre>

Attributes

#

This element has no attributes of its own. It supports the global attributes, such as class, id and hidden.

More examples

#
Project directory structure
HTML
<pre>
my-site/
β”œβ”€β”€ index.html
β”œβ”€β”€ css/
β”‚   └── style.css
└── js/
    └── app.js
</pre>
Preview
Special characters in a code block
HTML
<pre><code>&lt;a href="/courses"&gt;Courses &amp; paths&lt;/a&gt;</code></pre>
Preview

The source code has entities, and the preview shows plain <, >, and & characters.

Default CSS

#

Most browsers display this element with these default styles:

CSS
pre {
  display: block;
  font-family: monospace;
  white-space: pre;
  margin-block: 1em;
}

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Write a code block as <pre><code>, and a short inline fragment as plain <code>.
  • Add overflow-x: auto so long lines scroll horizontally instead of stretching the page on a phone.
  • Put ASCII art inside a <figure> with a description in <figcaption>, because a screen reader will read it out as a string of random symbols.

Related entries

#

Spotted a mistake or missing an example? Write to us.