Skip to main content

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>.

Prompt
A page using the kbd element to mark keyboard input: "Save the document by pressing Ctrl + S" with Ctrl + S as keyboard input.
Output: complete HTML page

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>.

Prompt
A page using the samp element to mark sample output from a program: a message reading "File not found." then "Press F1 to continue" with a line break.
Output: complete HTML page

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>.

Prompt
A page using the code element to show a piece of computer code: x = 5; y = 6; z = x + y;
Output: complete HTML page

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.

Prompt
A page that puts a code element inside a pre element so the extra whitespace and line breaks are preserved, showing x = 5; y = 6; z = x + y; on separate lines.
Output: complete HTML page

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.

Prompt
A page using the var element to mark variables in a sentence: the area of a triangle is 1/2 x b x h, where b is the base and h is the vertical height.
Output: complete HTML page

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.