HTML Computer Code Elements
HTML has several elements for showing user input and computer code, such as <kbd>, <samp>, <code>, and <var>.
HTML <kbd> For Keyboard Input
The <kbd> element marks keyboard input. Its content is shown in the browser's default monospace font.
Example
A keyboard shortcut marked with <kbd>.
Output: complete HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kbd</title>
</head>
<body>
<p>Save the document by pressing <kbd>Ctrl + S</kbd></p>
</body>
</html>
HTML <samp> For Program Output
The <samp> element marks sample output from a computer program. Its content is shown in the browser's default monospace font.
Example
Sample program output marked with <samp>.
Output: complete HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Samp</title>
</head>
<body>
<p>Message from my computer:</p>
<p><samp>File not found.<br>Press F1 to continue</samp></p>
</body>
</html>
HTML <code> For Computer Code
The <code> element marks a piece of computer code. Its content is shown in the browser's default monospace font.
Example
A piece of code marked with <code>.
Output: complete HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Code Element</title>
</head>
<body>
<code>
x = 5;
y = 6;
z = x + y;
</code>
</body>
</html>
Preserve Line-Breaks
The <code> element does not keep extra whitespace and line breaks. To keep them, put the <code> element inside a <pre> element.
Example
Code inside a <pre> to keep its line breaks.
Output: complete HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Code Pre</title>
</head>
<body>
<pre>
<code>
x = 5;
y = 6;
z = x + y;
</code>
</pre>
</body>
</html>
HTML <var> For Variables
The <var> element marks a variable in programming or in a math expression. Its content is usually shown in italic.
Example
Variables marked with <var> in a sentence.
Output: complete HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Var Element</title>
</head>
<body>
<p>The area of a triangle is: 1/2 x <var>b</var> x <var>h</var>, where <var>b</var> is the base, and <var>h</var> is the vertical height.</p>
</body>
</html>
Chapter Summary
To recap: the <kbd> element marks keyboard input, <samp> marks sample program output, <code> marks a piece of code, <var> marks a variable, and <pre> marks preformatted text.