The <pre> element is used for show text with spaces and line breaks preserved. You will run into it while reading other people’s HTML, and it is useful to know what job it does before copying the code.
What does <pre> mean?
Show text with spaces and line breaks preserved. The tag gives the browser a specific kind of content to work with. It is more helpful to choose a tag for its meaning than because of its default look.
Unlike an ordinary paragraph, pre keeps the source line breaks and repeated spaces. Its content should still escape literal markup characters.
A working HTML example
Here is a small example you can place in an HTML page and inspect in your browser:
<h2>Example terminal session</h2>
<pre><code>mkdir my-project
cd my-project
ls
</code></pre>
Reading the example
Find the <pre> part first. Notice which elements are around it and how its content or attributes are connected to those other elements.
In this example, <pre> appears alongside code, samp. That context is often just as important as the element itself.
The browser builds its document from these relationships. Any CSS changes appearance, while interactive JavaScript behavior must be provided separately when the example includes it.
When should you use it?
Use <pre> when you want to show text with spaces and line breaks preserved. A sensible example of this on a real website is the markup shown above; it gives the browser and accessibility tools a clearer job to work with.
Common companions are code, samp. Check the nesting requirements before moving the element into a different location.
Try it yourself
Add two spaces and a line break to the sample text and compare it with a normal paragraph.
Common Beginner Mistakes
- Do not use pre to align an entire page or substitute for CSS layout.
- Picking
<pre>only because it looks a certain way instead of checking what it means. - Forgetting to inspect the surrounding markup when an element does not behave as expected.
Key Takeaways
<pre>helps show text with spaces and line breaks preserved.- Unlike an ordinary paragraph, pre keeps the source line breaks and repeated spaces. Its content should still escape literal markup characters.
- Start with meaningful markup, then add styling or scripting only when the page needs it.