HTML
π 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:
-
<code>β Code snippets -
<kbd>β Keyboard input -
<samp>β Program output -
<var>β Variables -
<pre>β Preformatted text
How to Use These Elements
<code> β For Writing Code
HTML
<code>x = 5; y = 6; z = x + y;</code>
- Used inline
- 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>
- Code structure is preserved
- Indentation and line breaks remain intact
- 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:
- They distinguish code from normal text
- Screen readers can interpret content more accurately
- Code examples look more organized
- 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.
