0
0
HtmlHow-ToBeginner · 3 min read

How to Create Preformatted Text in HTML | Simple Guide

Use the <pre> tag in HTML to create preformatted text. This tag preserves all spaces, tabs, and line breaks exactly as you write them in your code.
📐

Syntax

The <pre> tag wraps the text you want to display exactly as it appears in your HTML code. It preserves spaces, tabs, and line breaks without collapsing them.

  • <pre>: Starts the preformatted text block.
  • Text inside: The content you want to show with exact spacing and line breaks.
  • </pre>: Ends the preformatted text block.
html
<pre>
Your preformatted text here
Line breaks and    spaces are preserved
</pre>
Output
Your preformatted text here Line breaks and spaces are preserved
💻

Example

This example shows how the <pre> tag keeps the text spacing and line breaks exactly as typed, unlike normal HTML text.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Preformatted Text Example</title>
</head>
<body>
  <h2>Preformatted Text Example</h2>
  <pre>
    This is preformatted text.
    Notice how spaces and line breaks
    are preserved exactly.

    Tabs and    multiple spaces stay as is.
  </pre>
</body>
</html>
Output
This is preformatted text. Notice how spaces and line breaks are preserved exactly. Tabs and multiple spaces stay as is.
⚠️

Common Pitfalls

One common mistake is trying to use spaces or tabs in normal HTML text expecting them to show up exactly. HTML collapses multiple spaces into one unless inside a <pre> tag.

Another pitfall is using the <code> tag alone, which styles text as code but does not preserve spacing or line breaks.

html
<!-- Wrong way: spaces and line breaks ignored -->
<p>    This    text    has    extra    spaces.</p>

<!-- Right way: spaces and line breaks preserved -->
<pre>
    This    text    has    extra    spaces.
</pre>
Output
This text has extra spaces.
📊

Quick Reference

TagPurposePreserves Spaces and Line Breaks
Wraps preformatted textYes
Styles inline code textNo

Paragraph textNo

Key Takeaways

Use the
 tag to show text exactly as typed with spaces and line breaks preserved.
Normal HTML collapses multiple spaces and ignores line breaks outside
.
The tag styles code but does not preserve formatting.
Always close the
 tag to avoid layout issues.
Preformatted text is useful for code snippets, ASCII art, or fixed-width text.