Preformatted and Code Text
Preserve spaces and show code with pre and code.
Syntax
<pre><code>line 1
line 2</code></pre>The <pre> element displays preformatted text. It keeps spaces and line breaks exactly as written, and uses a fixed-width font.
The <code> element marks up a snippet of computer code. Combine <pre> and <code> to display code blocks.
Example
Loading editor…
Press Run to see the result.
When to use it
- A developer uses <pre> to display source code examples in a tutorial with preserved indentation.
- A terminal-style app uses <pre> to render command-line output with exact whitespace and line breaks.
- A data display page uses <pre> with <code> to show a formatted JSON response from an API.
More examples
Preformatted ASCII art
<pre> preserves all spaces and newlines exactly as written, making it ideal for ASCII art and diagrams.
<pre>
/\_/\
( o.o )
> ^ <
</pre>Code block inside pre and code
Wrapping <code> inside <pre> combines semantic code meaning with preserved formatting for display.
<pre><code>function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("World"));
</code></pre>Preformatted JSON API response
A language class on <code> enables syntax highlighting libraries like Prism.js while <pre> keeps indentation.
<pre><code class="language-json">{
"user": "alice",
"role": "admin",
"active": true
}
</code></pre>
Discussion