HTML · Chapter 30 of 45

HTML Computer Code Elements

HTML provides several tags for displaying computer code and technical output: <code> for inline code snippets, <pre> for preformatted text that preserves whitespace, <kbd> for keyboard input, and <samp> for sample program output.

Combining <pre> and <code> together is the standard way to display multi-line code blocks while preserving indentation and line breaks exactly as written.

Syntax
<pre><code>your code here</code></pre>

Code and pre

<code> styles text as monospace inline. <pre> preserves whitespace and line breaks exactly as typed, useful for code blocks or ASCII art.

Keyboard and sample output

<kbd> represents keyboard input like Ctrl+C. <samp> represents sample output from a program, often used in documentation and tutorials.

Example 1 (html)
<pre><code>function greet() {
  console.log("Hi");
}</code></pre>
Output
function greet() {
  console.log("Hi");
}

pre preserves the indentation and line breaks of the code exactly.

Example 2 (html)
<p>Press <kbd>Ctrl</kbd> + <kbd>C</kbd> to copy.</p>
Output
Press Ctrl + C to copy.

kbd visually represents keys the user should press.

Key points

  • <code> displays inline code in monospace font.
  • <pre> preserves whitespace and line breaks exactly.
  • <kbd> represents keyboard input.
  • <samp> represents sample program output.
💡 Note: Combine <pre><code> for realistic multi-line syntax-highlighted code blocks.

📝 Quick Quiz

1. Which tag preserves whitespace and line breaks exactly?

2. Which tag represents keyboard input?

3. What is the common combination for multi-line code blocks?