The <pre> element preserves whitespace, line breaks, and spacing exactly as written in your HTML source. Normal HTML collapses extra whitespace — <pre> is the one place it doesn't.
Syntax
<pre>
Exact
spacing
is kept.
</pre>
Basic Example
<pre>
function greet(name) {
return "Hello, " + name;
}
</pre>
Browser output: the code appears exactly as typed — indentation, line breaks and all — in a monospace font, the browser's default styling for <pre>.
How It Works
The browser disables whitespace collapsing for everything inside <pre> and switches to a monospace font by default. It does not disable HTML parsing though — any real <, >, or & characters inside a <pre> block still need to be escaped as <, >, and &, exactly like anywhere else in HTML — this entire notes site relies on that rule to show HTML code as visible text.
Important Attributes
| Attribute | Purpose |
|---|---|
| — none — | Only universal global attributes apply |
Real-World Example
<pre><code>
<div class="card">
<h3>Product Name</h3>
</div>
</code></pre>
Wrapping <code> inside <pre> — the standard pattern for a multi-line code block on documentation sites, technical blogs, and this notes hub. See code for the full pairing explanation.
Common Mistakes
- Forgetting to escape
<,>, and&inside<pre>— whitespace preservation does not mean HTML parsing is turned off - Using
<pre>on regular paragraph text just to control spacing — for that, use the CSSwhite-spaceproperty on a normal element instead
Best Practices
- Pair
<pre>with<code>for actual code samples - Always escape special characters inside it
- Avoid it as a general-purpose layout/spacing trick
Accessibility Considerations
Screen readers may read verbatim/code content character-by-character in some configurations, which can be verbose for long blocks. Consider a brief plain-language summary alongside long <pre> blocks when the exact content matters to understanding the page.
SEO Considerations
Large blocks of unformatted code contribute little to a page's topical text signals — useful content, but not a substitute for explanatory prose around it.
Browser & Modern HTML Notes
A long-standing, stable element unlikely to change — every browser has supported it consistently since the earliest versions of HTML.
Mini Practice
- Display a short code snippet using
<pre><code>, correctly escaping any angle brackets inside it. - Recreate a simple piece of ASCII art inside a
<pre>block and confirm the spacing is preserved.