Skip to main content
Share:

Pre Tag

intermediate

Part of HTML Content & Structure

Theory

The <pre> element displays text exactly as written in the HTML source — preserving spaces, tabs, and line breaks. Browsers render it in a monospace font by default.

Preserving Whitespace

In normal HTML, multiple spaces and line breaks collapse into a single space. The <pre> tag changes this behavior, making it ideal for:

  • Code snippets and source code display
  • ASCII art
  • Poetry where exact spacing matters
  • Tabular data rendered with spaces

Combining with <code>

For code display, nest <code> inside <pre> to semantically mark the content as code while preserving formatting:

<pre><code>
function hello() {
  console.log("Hello, World!");
}
</code></pre>

Accessibility Considerations

Screen readers may read <pre> content character by character. For long code blocks, consider providing a text alternative or using the aria-label attribute to summarize the content.

Styling

Use CSS to customize <pre> appearance: background, padding, border, overflow-x: auto for horizontal scrolling on long lines, and font-family to control the monospace font.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Pre Tag Demo</title>
  <style>
    pre { background: #f4f4f4; padding: 15px; border-radius: 5px; overflow-x: auto; }
    code { font-family: "Courier New", monospace; }
  </style>
</head>
<body>
  <h1>Code Examples</h1>
 
  <h2>JavaScript Function</h2>
  <pre><code>function greet(name) {
  const message = "Hello, " + name + "!";
  console.log(message);
  return message;
}
 
greet("World");</code></pre>
 
  <h2>ASCII Art</h2>
  <pre>
    /\_/\
   ( o.o )
    &gt; ^ &lt;
  </pre>
</body>
</html>

Exercises

Display a Code Snippet

easy

Create an HTML page with an h1 heading 'Code Examples'. Use a pre tag with a nested code tag to display a short function in a language of your choice (JavaScript, Python, or CSS).

Expected Output:

A page with a heading and a preformatted code block that preserves indentation and line breaks exactly as written.

Mini Quiz

Mini Quiz