HTML <pre> Tag โ Preformatted Text
๐ Introduction
The <pre> tag is used to display preformatted text in HTML.
It preserves:
- Spaces
- Line breaks
- Indentation
Unlike normal text, HTML will not remove extra spaces inside <pre>.
๐งฑ Syntax
<pre>
Your text here
</pre>
๐ก Example
<!DOCTYPE html>
<html>
<head>
<title>Pre Tag Example</title>
</head>
<body>
<h1>Without pre</h1>
<p>Hello World</p>
<h1>With pre</h1>
<pre>
Hello World
This is preserved formatting
Indentation is kept
</pre>
</body>
</html>
๐ฅ๏ธ Output Explanation
Without <pre>:
- Multiple spaces are ignored
- Text appears normally
With <pre>:
- Spaces are preserved
- Line breaks are kept
- Indentation is shown exactly as written
๐ฏ When to Use <pre>
Use <pre> for:
- Code snippets
- ASCII art
- Structured text output
- Logs or formatted data
Example:
<pre>
function hello() {
console.log("Hello World");
}
</pre>
๐ก Why <pre> is Important
- Keeps formatting exactly as written
- Useful for tutorials and documentation
- Common in coding websites
โก <pre> + <code> (Best Practice)
For code display, combine both:
<pre><code>
function test() {
return "Hello";
}
</code></pre>
โ <pre> preserves formatting
โ <code> indicates code meaning
๐ซ Common Mistakes
- Using
<pre>for normal text โ - Forgetting that it affects spacing โ
- Using it for layout design โ
๐จ Styling <pre>
You can improve appearance with CSS:
<pre style="background:#111; color:#0f0; padding:10px;">
Code here
</pre>
๐งช Mini Exercise
Create a page that shows:
- A normal paragraph
- A
<pre>block showing:- A simple function
- Proper indentation
๐ Compare how both are displayed