HTML provides several elements for displaying computer code, programming instructions, and technical content. These elements help preserve formatting, distinguish code from regular text, and provide semantic meaning for screen readers and search engines.
Code Elements Overview
The following elements are used to display computer code in HTML:
Basic Code Elements
The <code> element defines a piece of computer code:
<!-- Inline code -->
<p>Use the <code>console.log()</code> function to output messages.</p>
<!-- Keyboard input -->
<p>Press <kbd>Ctrl</kbd> + <kbd>C</kbd> to copy.</p>
<!-- Variable output -->
<p>The result is: <samp>42</samp></p>
<!-- Variable name -->
<p>Initialize the <var>userCount</var> variable.</p>
Preformatted Text
The <pre> element defines preformatted text, preserving both spaces and line breaks. It's perfect for displaying code blocks:
<!-- Preformatted text preserves whitespace -->
<pre>
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("World");
</pre>
The <code> Element
The <code> element defines a piece of computer code:
Inline Code
The inline <code> element defines a piece of computer code. It's typically displayed in a monospace font and used for short code snippets within text:
<p>The <code>if</code> statement checks a condition.</p>
<p>Use <code>document.getElementById()</code> to select elements.</p>
<p>The <code>Array.prototype.map()</code> method creates a new array.</p>
<p>In Python, use <code>print()</code> to display output.</p>
<p>CSS uses <code>color: red;</code> to set text color.</p>
Code with Variables
When using <code> to display code snippets, you can include variables and function names for clarity:
<p>The function <code>calculateTotal(price, tax)</code> returns the final amount.</p>
<p>Initialize the variable with <code>let count = 0;</code>.</p>
<p>The CSS selector <code>.container > .item</code> targets direct children.</p>
The <pre> Element
The <pre> element defines preformatted text, preserving both spaces and line breaks. It's perfect for displaying code blocks:
Preformatted Text
When using <pre> to display code blocks, the text is displayed in a fixed-width font, and whitespace is preserved. This makes it ideal for showing code examples, configuration files, or any content where formatting is important:
<pre>
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Calculate the 10th Fibonacci number
const result = fibonacci(10);
console.log(result);
</pre>
Pre with Code
For better semantics and styling, you can combine <pre> with <code> to indicate that the content is code:
<pre><code>
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quicksort(left) + middle + quicksort(right)
numbers = [3, 6, 8, 10, 1, 2, 1]
sorted_numbers = quicksort(numbers)
print(sorted_numbers)
</code></pre>
File Contents
The <pre> element is also useful for displaying the contents of configuration files, logs, or any text where formatting is crucial:
<pre>
# Configuration file
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html;
}
location /api {
proxy_pass http://localhost:3000;
}
}
</pre>
The <kbd> Element
The <kbd> element represents keyboard input. It's used to show keys or key combinations that users should press:
Keyboard Input
When using the <kbd> element, you can display individual keys or combinations of keys that users should press. This is especially useful in tutorials, documentation, or any content that provides instructions for keyboard shortcuts:
<p>Press <kbd>Enter</kbd> to submit the form.</p>
<p>Use <kbd>Ctrl</kbd> + <kbd>S</kbd> to save the document.</p>
<p>Press <kbd>Alt</kbd> + <kbd>Tab</kbd> to switch windows.</p>
<p>To copy, press <kbd>Ctrl</kbd> + <kbd>C</kbd>.</p>
<p>Delete the item with <kbd>Delete</kbd> or <kbd>Backspace</kbd>.</p>
Complex Key Combinations
For more complex key combinations, you can use multiple <kbd> elements together:
<p>Restart: <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>Delete</kbd></p>
<p>Force quit: <kbd>Command</kbd> + <kbd>Option</kbd> + <kbd>Esc</kbd></p>
<p>Screenshot: <kbd>Win</kbd> + <kbd>Shift</kbd> + <kbd>S</kbd></p>
<p>Lock screen: <kbd>Win</kbd> + <kbd>L</kbd></p>
The <samp> Element
The <samp> element represents sample output from a program or computer system:
Sample Output
When you want to display sample output from a program, command line, or any computer system, the <samp> element is ideal. It helps differentiate output from regular text and provides a clear visual distinction:
<p>The program returned: <samp>Hello, World!</samp></p>
<p>Error message: <samp>File not found: /path/to/file.txt</samp></p>
<p>Calculation result: <samp>42</samp></p>
<p>Server response: <samp>200 OK</samp></p>
<p>Database query returned: <samp>15 rows affected</samp></p>
Command Line Output
For command line examples, you can use <samp> to show the expected output of commands:
<pre>$ node server.js
<samp>Server running on port 3000</samp>
$ curl http://localhost:3000
<samp>{"status": "ok", "message": "Hello, World!"}</samp>
</pre>
The <var> Element
The <var> element defines a variable in programming or mathematical expressions:
Variables
When you want to indicate that a word or phrase is a variable in a programming context or a mathematical expression, the <var> element is appropriate. It typically renders the text in italics to distinguish it from regular text:
<p>Initialize the <var>counter</var> variable to zero.</p>
<p>The formula is <var>E</var> = <var>mc</var>²</p>
<p>Set <var>userName</var> to the input value.</p>
<p>The function takes parameter <var>n</var> and returns <var>result</var>.</p>
<p>In the equation <var>y</var> = <var>mx</var> + <var>b</var>, <var>m</var> is the slope.</p>
Mathematical Expressions
For mathematical expressions, you can use <var> to indicate variables and constants:
<p>The area of a circle is <var>A</var> = <var>ฯ</var><var>r</var>².</p>
<p>For a quadratic equation <var>ax</var>² + <var>bx</var> + <var>c</var> = 0, the discriminant is <var>ฮ</var> = <var>b</var>² - 4<var>ac</var>.</p>
<p>The sum of an arithmetic series is <var>S</var> = <var>n</var>/2(<var>a</var>&sub1; + <var>a</var><sub>n</sub>).</p>
Combining Code Elements
These elements can be combined to create more complex code displays:
Tutorial Examples
When you want to demonstrate code examples, you can use a combination of these elements:
<p>To create a variable, use the <code>let</code> keyword: <code>let <var>name</var> = "John";</code></p>
<p>The function <code>console.log(<var>message</var>)</code> outputs: <samp>Hello, World!</samp></p>
<p>Press <kbd>F5</kbd> to refresh the page and see the updated <var>counter</var> value.</p>
<p>The CSS rule <code>color: <var>#ff0000</var>;</code> makes text red.</p>
Code Tutorials
For code tutorials, you can use a combination of <pre>, <code>, <var>, and <samp> to create clear and informative examples:
<h3>Creating an Array</h3>
<p>In JavaScript, create an array using:</p>
<pre><code>const <var>fruits</var> = ["apple", "banana", "orange"];
console.log(<var>fruits</var>[0]); // Outputs: <samp>apple</samp></code></pre>
<p>To add an element, use <code><var>fruits</var>.push("grape");</code></p>
Styling Code Elements
Here are some CSS styles for different code elements:
CSS Styling
Here is how to style each element:
/* Style code elements */
code {
background-color: #f4f4f4;
padding: 2px 4px;
border-radius: 3px;
font-family: 'Courier New', monospace;
font-size: 0.9em;
color: #e83e8c;
}
/* Style preformatted text */
pre {
background-color: #282c34;
color: #abb2bf;
padding: 1rem;
border-radius: 5px;
overflow-x: auto;
font-family: 'Courier New', monospace;
line-height: 1.5;
}
/* Style keyboard elements */
kbd {
background-color: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 3px;
padding: 2px 6px;
font-family: 'Courier New', monospace;
font-size: 0.85em;
box-shadow: 0 2px 0 #dee2e6;
}
/* Style sample output */
samp {
background-color: #d1ecf1;
color: #0c5460;
padding: 2px 4px;
border-radius: 3px;
font-family: 'Courier New', monospace;
}
/* Style variables */
var {
font-style: italic;
color: #6f42c1;
}
/* Code blocks with syntax highlighting */
pre code {
background: none;
padding: 0;
color: inherit;
}
/* Example syntax highlighting */
.keyword { color: #c678dd; }
.string { color: #98c379; }
.comment { color: #5c6370; font-style: italic; }
.function { color: #61afef; }
.variable { color: #e06c75; }
Advanced Styling
For more advanced styling, you can create themes for code blocks and interactive styles for keyboard elements:
/* Syntax highlighting theme */
pre {
background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
color: #f8f8f2;
border: 1px solid #4a5568;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
/* Different code themes */
.theme-dark code {
background-color: #2d3748;
color: #e2e8f0;
}
.theme-light code {
background-color: #f7fafc;
color: #2d3748;
}
/* Interactive keyboard buttons */
kbd:hover {
background-color: #e9ecef;
transform: translateY(1px);
box-shadow: 0 1px 0 #adb5bd;
}
kbd:active {
transform: translateY(2px);
box-shadow: none;
}
Accessibility Considerations
When using code elements, it's important to consider accessibility for all users, including those who rely on screen readers.
Screen Reader Support
Use ARIA labels and roles to provide context for screen readers when displaying code content:
<!-- Use ARIA labels for code blocks -->
<pre role="region" aria-label="JavaScript code example">
<code>function hello() { console.log("Hello!"); }</code>
</pre>
<!-- Add descriptions for complex code -->
<div role="img" aria-label="Python function that calculates factorial">
<pre><code>def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)</code></pre>
</div>
<!-- Use title attributes for abbreviations -->
<p>Use <code title="Application Programming Interface">API</code> to fetch data.</p>
Complete Example
Here is a complete example that combines all the code elements with styling and accessibility considerations:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Computer Code Elements Example</title>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
margin: 0;
padding: 20px;
background-color: #f4f4f4;
color: #333;
}
.container {
max-width: 1000px;
margin: 0 auto;
background-color: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h1 {
color: #2c3e50;
text-align: center;
margin-bottom: 30px;
}
/* Code element styling */
code {
background-color: #f8f9fa;
color: #e83e8c;
padding: 2px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.9em;
border: 1px solid #e9ecef;
}
/* Preformatted text styling */
pre {
background: linear-gradient(135deg, #282c34 0%, #1e1e1e 100%);
color: #abb2bf;
padding: 20px;
border-radius: 8px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 14px;
line-height: 1.5;
border: 1px solid #444;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
pre code {
background: none;
padding: 0;
color: inherit;
border: none;
}
/* Keyboard styling */
kbd {
background: linear-gradient(to bottom, #f8f9fa, #e9ecef);
border: 1px solid #adb5bd;
border-radius: 4px;
padding: 4px 8px;
font-family: 'Courier New', monospace;
font-size: 0.85em;
box-shadow: 0 2px 0 #adb5bd, inset 0 1px 0 #fff;
transition: all 0.1s ease;
}
kbd:hover {
background: linear-gradient(to bottom, #e9ecef, #dee2e6);
transform: translateY(1px);
box-shadow: 0 1px 0 #adb5bd, inset 0 1px 0 #fff;
}
kbd:active {
transform: translateY(2px);
box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
}
/* Sample output styling */
samp {
background-color: #d1ecf1;
color: #0c5460;
padding: 3px 6px;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 0.9em;
border: 1px solid #bee5eb;
}
/* Variable styling */
var {
font-style: italic;
color: #6f42c1;
font-weight: 500;
}
/* Section styling */
.section {
margin: 30px 0;
padding: 20px;
border: 1px solid #e9ecef;
border-radius: 8px;
background-color: #f8f9fa;
}
.section h2 {
color: #495057;
margin-top: 0;
border-bottom: 2px solid #dee2e6;
padding-bottom: 10px;
}
/* Interactive demo */
.demo {
background-color: #e3f2fd;
border-left: 4px solid #2196f3;
padding: 20px;
margin: 20px 0;
border-radius: 4px;
}
.demo h3 {
color: #1976d2;
margin-top: 0;
}
.button-group {
display: flex;
gap: 10px;
margin: 15px 0;
flex-wrap: wrap;
}
.btn {
padding: 8px 16px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: all 0.3s ease;
}
.btn-primary {
background-color: #3498db;
color: white;
}
.btn-primary:hover {
background-color: #2980b9;
transform: translateY(-2px);
}
#output {
background-color: #2d3748;
color: #e2e8f0;
padding: 15px;
border-radius: 4px;
font-family: 'Courier New', monospace;
margin: 15px 0;
min-height: 100px;
white-space: pre-wrap;
}
/* Syntax highlighting colors */
.keyword { color: #c678dd; }
.string { color: #98c379; }
.number { color: #d19a66; }
.comment { color: #5c6370; font-style: italic; }
.function { color: #61afef; }
.operator { color: #56b6c2; }
</style>
</head>
<body>
<div class="container">
<h1>HTML Computer Code Elements</h1>
<div class="section">
<h2>Inline Code Elements</h2>
<p>Use the <code><code></code> element for inline code like <code>console.log()</code> or <code>getElementById()</code>.</p>
<p>Keyboard shortcuts use <code><kbd></code>: Press <kbd>Ctrl</kbd> + <kbd>S</kbd> to save.</p>
<p>Sample output uses <code><samp></code>: The result is <samp>42</samp>.</p>
<p>Variables use <code><var></code>: Set <var>userName</var> to the input value.</p>
</div>
<div class="section">
<h2>Code Blocks</h2>
<p>Use <code><pre></code> for multi-line code blocks:</p>
<pre><code><span class="keyword">function</span> <span class="function">greet</span>(<span class="keyword">var</span> <var>name</var>) {
<span class="keyword">const</span> <var>message</var> = <span class="string">"Hello, "</span> + <var>name</var> + <span class="string">"!"</span>;
<span class="function">console</span>.<span class="function">log</span>(<var>message</var>);
<span class="keyword">return</span> <var>message</var>;
}
<span class="comment">// Call the function</span>
<span class="keyword">const</span> <var>result</var> = <span class="function">greet</span>(<span class="string">"World"</span>);
<span class="comment">// Output: Hello, World!</span></code></pre>
</div>
<div class="section">
<h2>Command Line Examples</h2>
<p>Terminal commands and output:</p>
<pre>$ npm install <var>package-name</var>
<samp>+ package-name@1.0.0
added 1 package in 2s</samp>
$ node <var>app.js</var>
<samp>Server running on http://localhost:3000</samp>
$ git <var>commit</var> -m <var>"Add new feature"</var>
<samp>[main 1a2b3c4] Add new feature
1 file changed, 5 insertions(+)</samp></pre>
</div>
<div class="section">
<h2>Mathematical Expressions</h2>
<p>Variables in mathematical formulas:</p>
<p>The quadratic formula: <var>x</var> = [-<var>b</var> ยฑ โ(<var>b</var>² - 4<var>ac</var>)] / 2<var>a</var></p>
<p>Area of a circle: <var>A</var> = <var>ฯ</var><var>r</var>²</p>
<p>Pythagorean theorem: <var>a</var>² + <var>b</var>² = <var>c</var>²</p>
</div>
<div class="demo">
<h3>Interactive Code Demo</h3>
<p>Click the buttons below to see different code examples and their output:</p>
<div class="button-group">
<button class="btn btn-primary" onclick="showJavaScript()">JavaScript</button>
<button class="btn btn-primary" onclick="showPython()">Python</button>
<button class="btn btn-primary" onclick="showCSS()">CSS</button>
<button class="btn btn-primary" onclick="showCommand()">Command Line</button>
</div>
<div id="output">Click a button to see code examples...</div>
</div>
<div class="section">
<h2>Best Practices Summary</h2>
<ul>
<li><strong>Use <code><code></strong> for short inline code snippets</li>
<li><strong>Use <code><pre></strong> for multi-line code blocks</li>
<li><strong>Use <code><kbd></strong> for keyboard input and shortcuts</li>
<li><strong>Use <code><samp></strong> for sample output from programs</li>
<li><strong>Use <code><var></strong> for variables in code or math</li>
<li><strong>Combine elements</strong> for complex examples</li>
<li><strong>Style appropriately</strong> for better readability</li>
</ul>
</div>
</div>
<script>
function showJavaScript() {
const output = document.getElementById('output');
output.innerHTML = `<span class="comment">// JavaScript Example</span>
<span class="keyword">const</span> <var>numbers</var> = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];
<span class="keyword">const</span> <var>squared</var> = <var>numbers</var>.<span class="function">map</span>(<var>n</var> => <var>n</var> * <var>n</var>);
<span class="function">console</span>.<span class="function">log</span>(<var>squared</var>);
<samp>[1, 4, 9, 16, 25]</samp>`;
}
function showPython() {
const output = document.getElementById('output');
output.innerHTML = `<span class="comment"># Python Example</span>
<span class="keyword">def</span> <span class="function">fibonacci</span>(<var>n</var>):
<span class="keyword">if</span> <var>n</var> <= <span class="number">1</span>:
<span class="keyword">return</span> <var>n</var>
<span class="keyword">return</span> <span class="function">fibonacci</span>(<var>n</var> - <span class="number">1</span>) + <span class="function">fibonacci</span>(<var>n</var> - <span class="number">2</span>)
<var>result</var> = <span class="function">fibonacci</span>(<span class="number">10</span>)
<span class="function">print</span>(<var>result</var>)
<samp>55</samp>`;
}
function showCSS() {
const output = document.getElementById('output');
output.innerHTML = `<span class="comment">/* CSS Example */</span>
.<var>container</var> {
<var>display</var>: <span class="string">grid</span>;
<var>grid-template-columns</var>: <span class="function">repeat</span>(<span class="string">auto-fit</span>, <span class="function">minmax</span>(<span class="number">250px</span>, <span class="number">1fr</span>));
<var>gap</var>: <span class="number">20px</span>;
<var>padding</var>: <span class="number">20px</span>;
}
.<var>card</var> {
<var>background-color</var>: <span class="string">#ffffff</span>;
<var>border-radius</var>: <span class="number">8px</span>;
<var>box-shadow</var>: <span class="number">0</span> <span class="number">2px</span> <span class="number">10px</span> <span class="function">rgba</span>(<span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">0.1</span>);
}`;
}
function showCommand() {
const output = document.getElementById('output');
output.innerHTML = `$ <var>git</var> <var>init</var>
<samp>Initialized empty Git repository</samp>
$ <var>git</var> <var>add</var> .
<samp>No output (files staged)</samp>
$ <var>git</var> <var>commit</var> -m <var>"Initial commit"</var>
<samp>[main (root-commit) abc1234] Initial commit
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 README.md</samp>
$ <var>git</var> <var>log</var> --<var>oneline</var>
<samp>abc1234 (HEAD -> main) Initial commit</samp>`;
}
</script>
</body>
</html>