HTML Computer Code

HTML provides several elements for displaying computer code, including programming code, commands, and terminal output.

These elements allow developers to display code snippets in a more readable and user-friendly format. In this answer, we will discuss the various HTML code elements and their usage.

The <code>Element:

<code>element is used to define inline code snippets, such as a single line of code.Is typically used in conjunction with other elements, such as <p>, <span>, or <li>, to display code within a larger block of text.

Example

<!DOCTYPE HTML>
  <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <title>Title of the Document</title>
    </head>
    <body>
      <h2>Computer Code</h2>
      <p>To install a package using NPM, type the following command</p>
      <div><code>npm install package-name</code></div>
    </body>
</html>

The <pre>Element:

<pre>element preserves whitespace and line breaks, making it ideal for displaying code with proper formatting.

Example

<!DOCTYPE HTML>
  <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
      <title>Title of the Document</title>
    </head>
    <body>
    <h2>Computer Code</h2>
    <p>The below JavaScript code will going to find the factorial of (5), and display it in alert function</p>
    <div>
      <pre><code>
      function factorial(n) {
        if (n === 0) {
          <return 1;
        } else {
          return n * factorial(n - 1);
        }
      }
      alert(factorial(5));
      </code></pre>
    </div>
    </body>
</html>

The <kbd>Element:

<code>element is used to define keyboard input, such as keyboard shortcuts or keys to press. It typically renders its contents with a monospace font and enclosed in a rectangular box.

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h2>Computer Code</h2>
    <p>To open the Developer Tools in Google Chrome, press <kbd>Ctrl+Shift+I</kbd>hhekke</p>
  </body>
</html>

The <var>Element:

<var>element is used to define a variable, such as a programming variable or a mathematical variable. It typically renders its contents in italicized font.

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h2>Computer Code</h2>
    <p>The formula to calculate the area of a circle is <var>A = πr<sup>2</sup></var>, where <var>r</var>is the radius</p>
  </body>
</html>

These are the various HTML code elements that are commonly used to display computer code on a webpage. By using these elements, developers can present code snippets in a more readable and user-friendly format. Lets us see how to achieve Semantics in the next chapter.