HTML Tags for Formatting Computer Code
Learn how to properly format code, user input, and variables in your HTML using `<code/>`, `<kbd/>`, `<samp/>`, `<pre/>`, and `<var/>` tags. This guide provides clear examples and explanations to improve the readability of your web content.
HTML Elements for Computer Code
HTML provides specific elements to format and display computer code, user input, and mathematical expressions clearly and consistently on web pages.
<samp>
: Sample Output
The <samp>
element is used to represent sample output from a computer program. The content within is typically displayed in a monospace font (a fixed-width font like Courier).
Example: <samp>
<samp>Message from my computer: File not found. Press F1 to continue.</samp>
Output
Message from my computer: File not found. Press F1 to continue.
<kbd>
: Keyboard Input
The <kbd>
element represents user input typed on a keyboard. It's also usually rendered in a monospace font.
Example: <kbd>
<p>Save the document by pressing <kbd>Ctrl + S</kbd></p>
Output
Save the document by pressing Ctrl + S
<code>
: Computer Code
The <code>
element is used to represent a fragment of computer code. Like <samp>
and <kbd>
, it typically uses a monospace font.
Example: <code>
<p>This is a code snippet: <code>x = 5; y = 6; z = x + y;</code></p>
Output
This is a code snippet: x = 5; y = 6; z = x + y;
Note: <code>
doesn't preserve whitespace or line breaks. For preserving formatting, use <pre>
.
<pre>
: Preformatted Text
The <pre>
element preserves whitespace and line breaks. It's useful for displaying code blocks where formatting is important.
Example: <pre>
<pre>
x = 5;
y = 6;
z = x + y;
</pre>
Output
x = 5;
y = 6;
z = x + y;
<var>
: Variables
The <var>
element represents a variable in a programming or mathematical context. The content is typically displayed in italics.
Example: <var>
<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 height.</p>
Output
The area of a triangle is: 1/2 x b x h, where b is the base, and h is the height.
Summary Table
Tag | Description |
---|---|
<code> |
Defines a fragment of computer code. |
<kbd> |
Defines keyboard input. |
<samp> |
Defines sample output from a program. |
<var> |
Defines a variable. |
<pre> |
Defines preformatted text (preserves whitespace). |
Using these elements improves the readability and accessibility of your web pages when you need to present code examples or other technical information.