Tutorials
THE WORLD'S LARGEST WEB DEVELOPER SITE

HTML Computer Code Elements

Computer Code

<code>
var x = 5;
var y = 6;
document.getElementById("demo").innerHTML = x + y;
</code>
Try it Yourself

HTML Computer Code Formatting

 

HTML usually uses variable letter size and spacing.

This is not what we require during the display of computer code.

The <kbd>, <samp>, and <code> elements are getting displayed in fixed letter size and spacing.

HTML <kbd> For Keyboard Input

 

The HTML <kbd> element is used for defining keyboard input:

Example

<kbd>File | Open...</kbd>

Result:

File | Open...
Try it Yourself

HTML <samp> For Computer Output

 

The HTML <samp> element is used for defining sample output from a computer program:

Example

<samp>
demo.example.com login: Apr 12 09:10:17
Linux 2.6.10-grsec+gg3+e+fhs6b+nfs+gr0501+++p3+c4a+gr2b-reslog-v6.189
</samp>

Result:

demo.example.com login: Apr 12 09:10:17 Linux 2.6.10-grsec+gg3+e+fhs6b+nfs+gr0501+++p3+c4a+gr2b-reslog-v6.189
Try it Yourself

HTML <code> For Computer Code

 

The HTML <code> element is used for defining a piece of programming code:

Example

<code>
var x = 5;
var y = 6;
document.getElementById("demo").innerHTML = x + y;
</code>

Result:

var x = 5; var y = 6; document.getElementById("demo").innerHTML = x + y;
Try it Yourself

You can notice that the <code> element is not preserving extra whitespace and line-breaks.

inorder to fix this, you can insert the <code> element inside a <pre> element:

Example

<pre>
<code>
var x = 5;
var y = 6;
document.getElementById("demo").innerHTML = x + y;
</code>
</pre>

Result:

var x = 5;

var y = 6;

document.getElementById("demo").innerHTML = x + y;

Try it Yourself

HTML <var> For Variables

 

The HTML <var> element is used to define a variable.

The variable can either be a variable in a mathematical expression or a variable in programming context:

Example

Einstein wrote: <var>E</var> = <var>m</var><var>c</var><sup>2</sup>.

Result:

Einstein wrote: E = mc2.
Try it Yourself

Test Yourself with Exercises

 

HTML Computer Code Elements


Tag Description
<code> Defines programming code
<kbd> Defines keyboard input 
<samp> Defines computer output
<var> Defines a variable
<pre> Defines preformatted text