HTML - Code & Computer Code

Overview

Estimated time: 25–35 minutes

Use semantic elements to represent code-related content: <code>, <pre>, <kbd>, <samp>, and <var>.

Examples

<p>Inline code: <code>const x = 42</code></p>
<pre><code>function hello(){\n  console.log('Hi');\n}</code></pre>

<p>Press <kbd>Ctrl</kbd>+<kbd>C</kbd> to copy.</p>
<p>Program output: <samp>Saved successfully.</samp></p>
<p>Let <var>n</var> be the number of items.</p>

Common Pitfalls

  • Forgetting to escape angle brackets inside code examples—use entities.
  • Losing formatting by omitting <pre> for multi-line code.

Exercises

  1. Show an inline code snippet and a multi-line preformatted snippet for a setup command.