References

Beginner-friendly references for web development, with live, editable examples.

The HTML <pre> tag

Element All modern browsers Updated
Quick answer

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 (&lt; for <, &amp; 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

Live example
<pre style="background:#f1f5f9;padding:10px;border-radius:6px;"><code>for (let i = 0; i &lt; 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 (&lt;, &amp;) so it displays rather than renders.
  • Add overflow-x: auto in CSS so long lines scroll instead of breaking the layout.

Frequently asked questions

What does the pre element do?
It preserves whitespace and line breaks exactly and renders the content in a monospace font, unlike normal HTML which collapses whitespace.
How do I make a code block in HTML?
Nest a <code> inside a <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?
Apply the CSS overflow-x: auto so long lines scroll horizontally within the block.
Why is my HTML showing as tags inside pre?
You need to escape it. Use &lt; for < and &amp; for & so the markup displays as text.