6. Preformatted Text (<pre> Tag)
Preserving spaces, tabs and Enter: what you write is what you see
Real-life analogy
Just as whatever you type on a typewriter is printed on the paper exactly as it is, with no auto-formatting, the <pre> tag does the same thing.
Explanation
Normally in HTML, no matter how many spaces (Spacebar) or Enters you press, the browser ignores them and shows just a single space.
But the <pre> (Preformatted Text) tag preserves every space, tab and new line you give it 100%. By default it appears in a Monospace font.
Golden rules
<pre>is best suited for showing poems, ASCII art or programming code.
Common mistake
Expecting a normal paragraph to preserve spaces. Remember, only <pre> works for preserving spaces.
Example code
<!DOCTYPE html>
<html>
<body style="font-family: sans-serif; padding: 15px;">
<!-- pre tag: all spaces and Enters will be preserved -->
<pre style="background: #0f172a; color: #38bdf8; padding: 15px; border-radius: 6px; font-size: 13px;">
Counting the stars
the night went by...
(Preformatted Text prints exactly as you write it)
</pre>
</body>
</html>
Quick quiz
Inside which tag are the spaces and line breaks shown by the browser exactly as written?
- <p>
- <code>
- <pre>
- <format>
Show answer
Answer: <pre>
The <pre> (Preformatted Text) tag doesn't let spaces and line breaks be lost.