📝 The <pre>
Tag in HTML: Preserving Text Formatting with Preformatted Blocks
The <pre>
tag is used to display preformatted text in HTML. It preserves both spaces and line breaks, showing text exactly as it is typed, making it perfect for code snippets, poetry, ASCII art, or any content where whitespace and line breaks matter.
📌 What Is the <pre>
Tag?
- The
<pre>
element displays text in a fixed-width (monospaced) font. - It preserves all whitespace characters (spaces, tabs) and line breaks.
- Unlike normal HTML text, where multiple spaces are collapsed into one,
<pre>
keeps spacing intact.
✅ Basic Syntax
<pre>
This is preformatted text.
Indentation and line breaks
are preserved exactly.
</pre>
🧩 Structure Diagram
<body>
└─ <pre>
Preformatted
Text block
</pre>
</body>
The browser renders the text inside <pre>
exactly as written.
🧪 Example 1: Displaying Code Snippet
<pre>
function greet() {
console.log("Hello, world!");
}
</pre>
This shows the code with indentation and line breaks preserved.
💡 Why Use <pre>
?
Benefit | Description |
---|---|
Preserves whitespace | Keeps spaces, tabs, and line breaks as-is |
Displays monospaced text | Uses a monospace font, ideal for code and tables |
Improves readability | Useful for technical documents or ASCII art |
Works well with <code> | Can be combined with <code> for semantic clarity |
🔧 Styling Tips
By default, <pre>
uses a monospace font and preserves formatting. You can customize it with CSS:
pre {
background-color: #f4f4f4;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
overflow-x: auto;
}
🧪 Example 2: Combining <pre>
with <code>
<pre><code>
let x = 10;
if (x > 5) {
console.log("x is greater than 5");
}
</code></pre>
This combination adds semantic meaning that the text is code, improving accessibility.
⚠️ Things to Remember
<pre>
preserves all whitespace — extra spaces and line breaks will appear in the browser.- Avoid using
<pre>
for large amounts of normal text, as it prevents text wrapping by default. - Use CSS (like
overflow-x: auto
) to make long lines scrollable instead of breaking layout.
🏁 Summary
The <pre>
tag is essential for displaying preformatted text on the web. Whether you’re showing code samples, ASCII art, or any text where spacing matters, <pre>
preserves your formatting exactly as you write it.
💡 Pro tip: For code snippets, combine
<pre>
with<code>
for best semantics and accessibility.