pre element
Use pre when spaces and line breaks are part of the meaning of the text, such as source code or a text layout.
What you will learn
- How
prepreserves whitespace - Why
preandcodeare often used together - How to display HTML source safely and accessibly
What does pre do?
pre means “preformatted text.” Browsers normally collapse repeated spaces and line breaks, but text inside pre is displayed with its whitespace preserved, usually in a monospace font.
Example: source code
<pre><code>
const message = "Hello";
console.log(message);
</code></pre>
Use code inside pre when the content is computer code. The pre element controls the preserved layout; code communicates what the content means.
Important details
- HTML tags inside
preare still parsed. Escape<,>, and&when showing HTML source. - Long lines can overflow on small screens, so allow horizontal scrolling with CSS or wrap the content carefully.
- If the layout made by spaces or line breaks is essential, provide an alternative explanation for screen readers and other presentations.
A simple style for long code
pre {
overflow-x: auto;
padding: 1rem;
white-space: pre;
}