πŸ“Œ HTML Code Elements

HTML provides special elements to display computer code and code-related text. These elements make the content visually distinct and semantically meaningful.

These tags are typically displayed using a monospace font, which makes code easier to read.

The main HTML code elements are:

  1. <code> β†’ Code snippets
  2. <kbd> β†’ Keyboard input
  3. <samp> β†’ Program output
  4. <var> β†’ Variables
  5. <pre> β†’ Preformatted text

How to Use These Elements

<code> β€” For Writing Code

HTML
<code>x = 5; y = 6; z = x + y;</code>
  1. Used inline
  2. Does not preserve spaces or line breaks

<pre> β€” For Writing Code

Keeps spaces, indentation, and line breaks exactly as written.

HTML

<pre>
    This text
    appears exactly
    as written.
</pre>
                

It is usually used together with <code> when displaying code.

Using <pre> + <code> Together

The best way to display code properly:

HTML

<pre>
    <code>
        x = 5;
        y = 6; 
        z = x + y;
    </code>
</pre>
                
  1. Code structure is preserved
  2. Indentation and line breaks remain intact
  3. Looks more professional

<kbd> β€” Keyboard Input

Indicates which keys the user should press.

HTML
<p> Press <kbd>Ctrl + S</kbd> to save.</p>

<samp> β€” Program Output

Represents the output shown after running a program.

HTML
<p> Program output: <samp>Operation successful</samp></p>

<var> β€” Variables

Used to represent variables in programming or mathematics.

HTML
<p> Equation: <var>a</var> + <var>b</var> = <var>c</var></p>

Why Should We Use These Elements?

These tags are important not only for appearance but also for semantic meaning:

  1. They distinguish code from normal text
  2. Screen readers can interpret content more accurately
  3. Code examples look more organized
  4. They improve user experience

Example Page

Below is a simple example using all these elements together:

HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Code Elements Example</title>
    </head>
    <body>
        <h1>HTML Code Elements</h1>

        <p>Press <kbd>Ctrl + S</kbd> to save.</p>

        <p>Program output:</p>
        <p><samp>Operation completed. Result: 42</samp></p>

        <p>Here is a code example:</p>
        <pre>
        <code>
            function sum(a, b) {
                return a + b;
            }

            let total = sum(5, 7);
            console.log(total);
        </code>
        </pre>

        <p>Formula: <var>x</var> = <var>a</var> + <var>b</var></p>

    </body>
</html>
                
  • 🎯 Short Summary

  • HTML provides special elements for displaying code:
  • <code> β†’ Inline code
  • <pre> β†’ Formatted text
  • <kbd> β†’ Keyboard input
  • <samp> β†’ Program output
  • <var> β†’ Variables

πŸ‘‰ Best practice: Use <pre> + <code> together for proper code display.