<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
Example
#<pre><code>function greet(name) {
return 'Hello, ' + name + '!';
}
console.log(greet('Ola'));</code></pre>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 < and &. 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
#<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
#<pre>
my-site/
βββ index.html
βββ css/
β βββ style.css
βββ js/
βββ app.js
</pre><pre><code><a href="/courses">Courses & paths</a></code></pre>The source code has entities, and the preview shows plain <, >, and & characters.
Default CSS
#Most browsers display this element with these default styles:
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: autoso 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
#- <code>A piece of computer code: the name of a variable, function, tag, or file, as well as a short listing.
- <samp>Sample output from a program: a message, a console response, or error text.
- <kbd>Input entered by the user: keys, keyboard shortcuts, and commands to type.
- <p>A paragraph of text.
- <br>A line break at the point itβs inserted, without starting a new paragraph.
Spotted a mistake or missing an example? Write to us.