0
0
HTMLmarkup~15 mins

Preformatted text in HTML - Deep Dive

Choose your learning style9 modes available
Overview - Preformatted text
What is it?
Preformatted text in HTML is a way to display text exactly as it is typed, including spaces, line breaks, and tabs. It uses the
 tag to preserve the original formatting of the text. This is useful when you want to show code, poetry, or any text where spacing matters. The browser does not change the spacing or line breaks inside this tag.
Why it matters
Without preformatted text, browsers collapse multiple spaces and ignore line breaks, making it hard to show text that relies on exact spacing. This would make displaying code snippets, ASCII art, or formatted data confusing or unreadable. Preformatted text solves this by keeping the text's original shape, helping readers understand the content as intended.
Where it fits
Before learning about preformatted text, you should understand basic HTML tags and how browsers handle whitespace. After this, you can learn about styling preformatted text with CSS or how to display code snippets with syntax highlighting.
Mental Model
Core Idea
Preformatted text shows exactly what you type, preserving spaces and line breaks without change.
Think of it like...
It's like writing a letter on graph paper where every space and line you make stays exactly as you put it, unlike normal paper where extra spaces might be ignored.
┌───────────────────────────────┐
│ <pre>                        │
│   Text inside here           │
│   keeps    all spaces        │
│   and line breaks exactly   │
│   as typed.                 │
│ </pre>                      │
└───────────────────────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding whitespace in HTML
🤔
Concept: Browsers normally ignore extra spaces and line breaks in HTML text.
In HTML, if you type multiple spaces or press Enter to create new lines, the browser will usually show just one space and ignore the line breaks. For example, typing "Hello World" will appear as "Hello World" in the browser.
Result
Text appears with single spaces and no visible line breaks despite multiple spaces or new lines in the code.
Knowing that browsers collapse whitespace explains why preformatted text is needed to preserve exact spacing.
2
FoundationIntroducing the <pre> tag
🤔
Concept: The
 tag tells the browser to keep all spaces and line breaks as they are.
When you wrap text inside
 and 
, the browser shows the text exactly as typed, including all spaces and line breaks. This is useful for code or text where formatting matters.
Result
Text inside
 displays with all original spaces and line breaks preserved.
The
 tag is a simple way to control how text formatting appears in the browser.
3
IntermediateCombining <pre> with other tags