SyntaxStudy
Sign Up
HTML Preformatted Text and Code
HTML Beginner 5 min read

Preformatted Text and Code

Preformatted Text and Code

The <pre> element displays text in a fixed-width font and preserves whitespace — spaces, tabs, and line breaks appear exactly as written in the HTML source. It is ideal for ASCII art or any content where spacing is meaningful.

Inline and Block Code

Use <code> for inline snippets of computer code within a sentence. For multi-line code blocks, wrap <code> inside <pre>. The <kbd> element represents keyboard input, <samp> represents sample output, and <var> represents a variable name.

  • <pre> — Preserves whitespace
  • <code> — Inline code fragment
  • <kbd> — Keyboard input
  • <samp> — Sample output
  • <var> — Variable name
Example
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Preformatted &amp; Code</title>
</head>
<body>
  <h1>Code Examples</h1>

  <p>Use <code>console.log()</code> to print output.</p>

  <pre><code>function greet(name) {
    return "Hello, " + name + "!";
}
console.log(greet("World"));</code></pre>

  <p>Press <kbd>Ctrl</kbd> + <kbd>S</kbd> to save.</p>

  <p>The program returned: <samp>Hello, World!</samp></p>

  <p>The variable <var>x</var> holds the count.</p>
</body>
</html>
Pro Tip

Always escape < as &lt; and > as &gt; inside <pre><code> blocks so the browser does not try to parse your code snippets as HTML tags.