HTML Computer Code Elements

HTML has several elements designed specifically to display computer code and keyboard input in a way that is meaningful, not just visually monospaced. Browsers render <code>, <kbd>, <samp>, and <var> in a monospace font by default, but each one has a distinct semantic meaning.

1) The code Element


<p>The <code>document.getElementById()</code> method returns an element by its id.</p>

The <code> element marks up a short fragment of computer code, such as a function name, a variable, or a line of a programming language.

Output

The document.getElementById() method returns an element by its id.

2) The kbd Element


<p>Press <kbd>Ctrl</kbd> + <kbd>C</kbd> to copy, and <kbd>Ctrl</kbd> + <kbd>V</kbd> to paste.</p>

The <kbd> element represents user keyboard input. It is commonly shown with a bordered, button-like style to imitate a physical key.

Output

Press Ctrl + C to copy, and Ctrl + V to paste.

3) The samp Element


<p>Running the script prints: <samp>File saved successfully.</samp></p>

The <samp> element represents sample output from a computer program or script — the opposite direction of <kbd>, which is input from the user.

Output

Running the script prints: File saved successfully.

4) The var Element


<p>The area of a circle is <var>A</var> = <var>π</var> × <var>r</var>2.</p>

The <var> element represents a variable name, used in a mathematical expression, a programming context, or a technical reference. Browsers usually render it in italics.

Output

The area of a circle is A = π × r2.

5) The pre Element


<pre>
function greet(name) {
    return "Hello, " + name;
}
</pre>

The <pre> element displays preformatted text. Whitespace, line breaks, and indentation are preserved exactly as written in the HTML source, and the text is shown in a monospace font. It is very often combined with <code>.

Output

function greet(name) {
    return "Hello, " + name;
}

6) Combined Example: A Mini Terminal Session


<pre>
<kbd>npm install</kbd>
<samp>added 42 packages in 3s</samp>

<kbd>npm start</kbd>
<samp>Server running at http://localhost:3000</samp>
</pre>

<kbd>, <samp> and <pre> combine well to recreate a realistic terminal transcript: commands typed by the user next to the output produced by the program.

Output

npm install
added 42 packages in 3s

npm start
Server running at http://localhost:3000

Best Practices:

  • Use <code> for code snippets, <kbd> for what the user types, and <samp> for what the program outputs.
  • Use <var> only for variable or placeholder names, not for general emphasis.
  • Wrap multi-line code in <pre> so indentation and line breaks are preserved.
  • Combine <pre> with <code> for a properly formatted, semantically correct code block.
  • Avoid using these tags purely for their monospace look — pick them based on meaning, and use CSS for styling.