Text & FormattingExtra· 25 min read

Showing Computer Code

Special tags for displaying code, keyboard keys and program output exactly as written.

What you will learn

  • Show inline and block code with <code> and <pre>
  • Use <kbd>, <samp> and <var> for keys, output and variables

Inline code and code blocks

Use <code> for a short piece of code inside a sentence. Use <pre> (preformatted) when you need to keep your spaces and line breaks exactly — perfect for multi-line code.

<code> inline and <pre> for blocks
<p>Use the <code>&lt;p&gt;</code> tag for paragraphs.</p>
<pre>
function hello() {
    console.log("Spaces are kept!");
}
</pre>
Live preview

Note: Normally the browser collapses many spaces into one. Inside <pre>, every space and line break is preserved exactly.

Keys, output and variables

TagUse for
<kbd>Keyboard input, e.g. press a key
<samp>Sample output from a program
<var>A variable or maths symbol
kbd, samp and var
<p>Save the file with <kbd>Ctrl</kbd> + <kbd>S</kbd>.</p>
<p>The program printed: <samp>Hello World</samp></p>
<p>The area is <var>length</var> × <var>width</var>.</p>
Live preview

Each tag signals what kind of text it wraps: <kbd> marks keys the user presses (often shown in a monospace, key-like style), <samp> marks text a program printed out, and <var> marks a variable or maths name (usually shown in italics). They mainly carry meaning, with a small built-in style on top.

Note: Output: Save the file with Ctrl + S. (the keys in a monospace, keyboard-style font) The program printed: Hello World (in monospace, like program output) The area is length × width. (the variable names in italics)

Q. Which tag preserves your exact spaces and line breaks?

Answer: <pre> (preformatted) keeps whitespace and line breaks exactly as written — ideal for code blocks.

✍️ Practice

  1. Show a three-line code snippet inside <pre> and confirm the indentation is preserved.
  2. Write a sentence describing a keyboard shortcut using <kbd> for each key.

🏠 Homework

  1. Document one HTML tag you learned, using <code> for the tag name and <pre> for an example.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →