HTML Computercode
In this page:
<code>Inline code</code>
<pre><code>Preformatted code</code></pre>
<kbd>Keyboard input</kbd>
The code Tag
The code tag is used to display inline code snippets or technical keywords. It styles the text in a monospace font (like Courier) to distinguish it from surrounding body paragraphs.
Example: The code Tag
<p>Run the <code>npm install</code> command.</p>
Preformatted Code Blocks (pre and code)
To display a multi-line code block with its original line breaks, indentation, and spaces preserved, you wrap your code element inside a pre (preformatted) tag.
Without the pre tag, the browser would collapse all your careful indentation and line breaks into a single line.
Example: Preformatted Code Blocks (pre and code)
<pre><code>function add(a, b) {
return a + b;
}</code></pre>
Styling Keyboard Inputs (kbd)
The kbd element is used to represent user keyboard inputs, such as command shortcuts or keys to press.
Browsers render the text inside kbd tags in a monospace font by default. This makes it easy to visually distinguish 'press Ctrl+S' instructions from regular body text.
Example: Styling Keyboard Inputs (kbd)
<p>Press <kbd>Ctrl</kbd> + <kbd>S</kbd> to save.</p>
Displaying Terminal Output (samp)
The samp tag is used to represent output data from a computer system, terminal program, or active script process, rendering the text in a monospace font by default.
This is commonly seen in tutorials that show a program's console output right below the code that produced it.
Example: Displaying Terminal Output (samp)
<p>The terminal displayed: <samp>Build successful</samp></p>
Defining Variables in Code (var)
The var tag is used to represent variables in mathematical formulas, code arguments, or technical equations. The browser displays the text in an italicized format by default.
This visual distinction helps readers immediately spot which parts of an example are placeholders versus fixed syntax.
Example: Defining Variables in Code (var)
<p>The formula is <var>x</var> + <var>y</var> = 10</p>
- Using the inline code tag alone to display multi-line code snippets, causing the formatting to break.
- Writing raw HTML tags (like ) inside code elements without escaping the brackets, which can crash your page layouts.
- Misusing kbd and samp as generic styling tags rather than as semantic technical notations.
- The code tag styles inline technical terms, properties, and filenames in a monospace font.
- To preserve line breaks and spacing inside multi-line code blocks, wrap your code tag inside a pre tag.
- Use kbd to represent keyboard inputs, samp to display system output logs, and var to style technical variables.
Standard computercode tags and monospace styles are supported natively by all web browsers.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: