HTML Computercode

HTML Computer Code Elements

Computer Code

<code>
var x = 5;
var y = 6;
document.getElementById("demo").innerHTML = x + y;
</code>
Click here to Run the Program

HTML Computer Code Formatting

  • HTML normally uses variable letter size and spacing.
  • This is not what we want when displaying computer code.
  • The <kbd>, <samp>, and <code> elements are all displayed in fixed letter size and spacing.

HTML <kbd> For Keyboard Input

The HTML <kbd> element defines keyboard input :

<!DOCTYPE html>
<html>
<body>

<p>The kbd element represents keyboard input : </p>

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

</body>
</html>
Click here to Run the Program

HTML <samp> For Computer Output

The HTML <samp> element defines sample output from a computer program :

<!DOCTYPE html>
<html>
<body>

<p>The samp element represents sample output from a computer program : </p>

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

</body>
</html>
Click here to Run the Program

HTML <code> For Computer Code

The HTML <code> element defines a piece of programming code :

<!DOCTYPE html>
<html>
<body>

<p>Programming code example : </p>

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

</body>
</html>
Click here to Run the Program

Notice that the <code> element does not preserve extra whitespace and line-breaks.

To fix this, you can put the <code> element inside a <pre> element :

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>
Click here to Run the Program

HTML <var> For Variables

  • The HTML <var> element defines a variable.
  • The variable could be a variable in a mathematical expression or a variable in programming context :
<!DOCTYPE html>
<html>
<body>

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

</body>
</html>
Click here to Run the Program

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