On this page11 sections
Lecture 025: Computer Code Elements
| Category | 5: Code, Characters & Standards |
| Lecture | 025 of 048 |
| Estimated video length | 8 min |
| Target | HTML5 · any modern browser |
| Level | Beginner |
Tutorials, documentation and help pages often show code, keyboard keys and program output. HTML has a small element for each one, so the meaning is clear and the browser shows them in a fixed-width (monospace) font.
Learning Objectives
- Mark up code with
<code>and preserve layout with<pre> - Show keyboard input with
<kbd>, program output with<samp>and variables with<var>
1. <code>: a Piece of Code
Example
<p>Use the <code>print()</code> function to show output in Python.</p>2. <pre> + <code>: a Block of Code
<pre> keeps every space and line break exactly as written. Put <code> inside it for a
code block.
Example
<pre><code>function greet(name) {
return "Hello, " + name;
}</code></pre>Remember to write < as < inside code blocks, or the browser will read it as a tag:
<pre><code><p>This is a paragraph</p></code></pre>3. <kbd>: Keyboard Input
Example
<p>Press <kbd>Ctrl</kbd> + <kbd>C</kbd> to copy, and <kbd>Ctrl</kbd> + <kbd>V</kbd> to paste.</p>A little CSS makes keys look like real keys:
<style>
kbd { border: 1px solid #adb5bd; border-bottom-width: 3px; border-radius: 4px; padding: 1px 6px; background: #f8f9fa; }
</style>
<p>Save with <kbd>⌘</kbd> + <kbd>S</kbd>.</p>4. <samp>: Program Output
Example
<p>If the file is missing, you'll see: <samp>Error 404: Not Found</samp></p>5. <var>: A Variable
Used in maths and programming explanations. Browsers show it in italics.
Example
<p>The area of a rectangle is <var>width</var> × <var>height</var>.</p>Quick Reference
| Element | Meaning |
|---|---|
<code> | A piece of computer code |
<pre> | Preformatted text (keeps spaces and line breaks) |
<kbd> | Keyboard input |
<samp> | Sample output from a program |
<var> | A variable |
Common Beginner Mistakes
1. Raw < inside code. Write < and > for angle brackets.
2. <code> alone for multi-line code. Line breaks collapse. Wrap it in <pre>.
3. Using <pre> just for indentation. Use CSS margins and padding for layout.
Practice Questions
- Which element shows a short piece of code inside a sentence?
- Which element keeps line breaks and spaces exactly as typed?
- Mark up "Press Enter" so that Enter is shown as a keyboard key.
- Which element is for the output of a program?
- How do you show the text
<h1>inside a code block?
Practice Answers
<code><pre><p>Press <kbd>Enter</kbd></p><samp>- Write it with entities:
<h1>
Key Takeaways
<code>for code,<pre><code>for blocks of code.<kbd>for keys,<samp>for output,<var>for variables.- Escape
<and>as<and>inside code.