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>
- Easy to use with a learn-by-doing approach
- Offers quality content
- Gamified in-browser coding experience
- The price matches the quality
- Suitable for learners ranging from beginner to advanced
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
- Nanodegree programs
- Suitable for enterprises
- Paid Certificates of completion
- A wide range of learning programs
- University-level courses
- Easy to navigate
- Verified certificates
- Free learning track available
- University-level courses
- Suitable for enterprises
- Verified certificates of completion
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.