Skip to main content

HTML Tags

HTML <pre> Tag

Written by Updated HTML <pre> Tag exercises

Normally HTML squeezes every run of spaces and line breaks into one space. Inside a pre tag it does not: the text shows exactly as you typed it, in a fixed-width font. That makes it the right tag for code, ASCII art and anything where alignment matters.

Syntax

html

<pre>Preformatted text goes here</pre>

There are no special attributes, only the global ones such as class, id, style and title.

Example

html

<!DOCTYPE html>
<html>
<head>
  <title>PRE Tag Example</title>
  <style>
    .code-sample {
      background-color: #f4f4f4;
      border: 1px solid #ccc;
      padding: 10px;
      font-family: "Courier New", monospace;
      color: #333;
      border-radius: 6px;
    }
  </style>
</head>
<body>
  <h1>Preformatted Text Example</h1>
  <p>The &lt;pre&gt; tag preserves spacing and line breaks exactly as they appear in the source code.</p>

  <pre class="code-sample" id="example1" title="Sample Code">
function greetUser() {
    console.log("Hello, World!");
}
  </pre>

  <p>Notice how indentation and line breaks are preserved inside the &lt;pre&gt; tag.</p>
</body>
</html>

The function keeps its indentation and line breaks, and appears in a monospace font. The same text in a <p> would collapse into a single line.

Showing code: pre plus code

For code samples, put a <code> inside the <pre>. pre keeps the spacing; code tells browsers, search engines and screen readers that the text is code.

A code block

html

<pre><code>const total = price * quantity;
console.log(total);</code></pre>

Three things that trip people up

  • HTML inside pre still runs. If your code sample contains <div>, the browser treats it as a real div. Write &lt; instead of < and &gt; instead of >, as the example above does in its paragraphs.
  • The first line break is skipped, the last one is not. A line break straight after <pre> is ignored, but spaces and line breaks before </pre> do show, which can leave an empty line at the bottom.
  • Long lines do not wrap. They run off the side on phones. Add overflow-x: auto so the block scrolls, or white-space: pre-wrap so lines wrap but spaces are kept.

Browser Support

Chrome
Edge
Firefox
Safari
Opera
IE9+
YesYesYesYesYesYes

For a single line break inside normal text, the br tag is usually all you need.

HTML <pre> Tag exercises

Keep the spacing

Show these two lines so that the line break and the two spaces before bread stay exactly as typed: shopping on the first line, and two spaces and bread on the second.

Result

Check your answer to see it here.