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.
<p>Use the <code><p></code> tag for paragraphs.</p>
<pre>
function hello() {
console.log("Spaces are kept!");
}
</pre>Note: Normally the browser collapses many spaces into one. Inside <pre>, every space and line break is preserved exactly.
Keys, output and variables
| Tag | Use for |
|---|---|
<kbd> | Keyboard input, e.g. press a key |
<samp> | Sample output from a program |
<var> | A variable or maths symbol |
<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>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?
✍️ Practice
- Show a three-line code snippet inside
<pre>and confirm the indentation is preserved. - Write a sentence describing a keyboard shortcut using
<kbd>for each key.
🏠 Homework
- Document one HTML tag you learned, using
<code>for the tag name and<pre>for an example.