HTML

Introduction to Web and HTML

How the Web Works What is HTML Why Learn HTML

Preformatted Text (`<pre>`)

Preformatted Text (<pre>)

The <pre> element in HTML is used to display text exactly as it appears in the HTML code, preserving whitespace, line breaks, and formatting. It's particularly useful when you need to display code snippets, ASCII art, or any content where preserving the layout is crucial. Here's how to use the <pre> element effectively:

Syntax

To create preformatted text in HTML, you use the <pre> element. Open it with <pre> and close it with </pre>. Place your text or code snippet between the opening and closing tags:

<pre>
  This is preformatted text.
  It preserves line breaks and spacing.
  Special characters like < and > are displayed as-is.
</pre>

Use of <pre>

  1. Code Snippets: The <pre> element is often used to display code snippets. It's a common practice in technical documentation, programming tutorials, and blogs where code formatting is essential for readability.

    <pre>
      function helloWorld() {
        console.log("Hello, World!");
      }
    </pre>
    
  2. ASCII Art: When creating ASCII art, which relies on precise positioning of characters, <pre> ensures that your artwork maintains its intended layout.

    <pre>
        _   _
       /     \
      ( o o )
     /   *   \
     \       /
      ' --- '
    </pre>
    
  3. Whitespace Preservation: Any whitespace characters, such as spaces or tabs, are preserved within <pre>. This is particularly useful when you want to display text with precise formatting.

    <pre>
    Indentation
        is
    preserved.
    </pre>
    

Styling Preformatted Text

The <pre> element preserves text formatting and spacing but doesn't inherently apply styling. You can use CSS to style the text inside the <pre> element, such as setting the font family, color, and background color.

<!-- HTML -->
<pre>
  This is preformatted text with <span class="highlight">styling</span>.
</pre>

<!-- CSS -->
<style>
  pre {
    font-family: 'Courier New', monospace;
    background-color: #f0f0f0;
  }

  .highlight {
    color: red;
  }
</style>

Accessibility Considerations

While <pre> is useful for displaying preformatted text, ensure that your content remains accessible. For code snippets, consider providing alternative text explanations or links to more detailed documentation. For ASCII art or complex formatting, provide textual descriptions for screen readers.

In summary, the <pre> element is essential for displaying text exactly as it appears in the HTML code. It's commonly used for code snippets and any content where preserving layout and spacing is crucial for understanding and readability.