The HTML <pre> tag
The HTML <pre> element displays preformatted text — whitespace and line breaks are preserved exactly, in a monospace font. Wrap a <code> inside it for a code block: <pre><code>…</code></pre>.
Overview
The <pre> element renders its content exactly as written — every space, tab and newline is preserved — in a monospace font. That makes it the right element for content whose formatting is meaningful: code listings, ASCII art, terminal output, and fixed-layout text.
The standard pattern for a code block is a <code> nested inside a <pre> — the <pre> keeps the layout, and the <code> adds the semantic meaning that the content is source code.
Two practical notes: escape the special characters when the content includes literal HTML (< for <, & for &), and apply the CSS overflow-x: auto so that long lines scroll within the block rather than stretching the page layout.
Syntax
<pre><code>function hi() {
return 'hello';
}</code></pre>
Example
<pre style="background:#f1f5f9;padding:10px;border-radius:6px;"><code>for (let i = 0; i < 3; i++) {
console.log(i);
}</code></pre>
Best practices
- Use
<pre>whenever whitespace and line breaks must be preserved — code, ASCII art, fixed layouts. - For code, nest a <code> inside it to add code semantics.
- Escape literal HTML (
<,&) so it displays rather than renders. - Add
overflow-x: autoin CSS so long lines scroll instead of breaking the layout.
Frequently asked questions
What does the pre element do?
How do I make a code block in HTML?
<pre>: the pre preserves formatting and the code marks it as source code.How do I stop long lines in pre from breaking the layout?
-x: auto so long lines scroll horizontally within the block.Why is my HTML showing as tags inside pre?
< for < and & for & so the markup displays as text.