TL;DR – HTML computer code elements are used to display computer output or code fragments.
Contents
What's Special About Computer Code
Normally, HTML uses various letter sizes, fonts, and spacing. You can adjust it with CSS properties like font-size, font-family, and so on.
HTML computer code is displayed with fixed letter size, font, and spacing. You may want to replicate this look when adding HTML code snippets in your web page. There are a few HTML elements to help you achieve this goal:
Element | Defines |
---|---|
<code> | Computer code |
<samp> | Computer output |
<kbd> | Keyboard input |
<var> | Variables |
<pre> | Preformatted text (e.g., an HTML code block) |
Tags for HTML Code Snippet Formatting
The HTML <code> tags define an HTML code snippet on your website. The text inside the <code>
tags will be displayed in a default monospace font:
The <samp> element depicts the output of the system or computer in your HTML document. The font, size, and spacing remain the same as with other HTML code elements:
This is an output of a program ->
<samp>
a + b + c = alotOfNumbers
</samp>
While technically the <kbd> element also defines a fragment of HTML code, according to HTML syntax, it should only be used to display a keyboard input:
The <var> element defines a variable. It can be used to define variables in mathematics or programming:
<p>Einstein's best known equation goes like this:
<var>E</var> = <var>mc</var><sup>2</sup></p>
Preformatting HTML Code Blocks
Just like <p> elements, HTML code tags ignore all white spaces and line breaks. If you need to convey the structure of an HTML code block with indentations, you should put the <code>
element inside a <pre> element:
<pre>
<code>
variables :
a
b
c
I can write my code anyway I like
and the "pre" tag will keep it that way!
</code>
</pre>
HTML Code: Useful Tips
- If all you need to keep is a line break, you can also use the <br> tag to insert one instead of preformatting the whole HTML code block.
- You can highlight the syntax in your HTML code snippets by using a JavaScript library, such as Highlight.js or Prism.js.