Code and Preformatted Text
You'll learn how to display computer code, keyboard input, and other technical text properly in HTML.
What's the Difference?
When you're writing about programming or showing examples of code on a webpage, regular text formatting doesn't cut it. You need special elements that preserve spacing, use monospace fonts, and communicate meaning to both browsers and assistive technologies.
The Five Code-Related Elements
<code> – Inline Code Snippets
Use this for short pieces of code within a sentence. It applies a monospace font and signals "this is computer code."
Example: The <code> element makes text look like this.
<pre> – Preformatted Text
This preserves all whitespace—spaces, tabs, line breaks. Perfect for multi-line code blocks or ASCII art. Browsers won't collapse your carefully formatted spacing.
<kbd> – Keyboard Input
Marks text the user should type. Think keyboard shortcuts or commands.
Example: Press <kbd> to show Ctrl+C.
<samp> – Sample Output
Displays example output from a program or system—what the computer shows back to you.
<var> – Variables
Represents mathematical variables or programming placeholders, usually rendered in italics.
Example: Let <var> represent x in the equation.
Combining Them
You'll often wrap <code> inside <pre> for multi-line code blocks that need both semantic meaning and preserved formatting.
Why This Matters
These elements aren't just about looks—they're about semantics. Screen readers announce them differently, search engines understand the content type, and your styling becomes more meaningful and maintainable.
Key Takeaway: Use <code> for inline code, <pre> to preserve formatting, <kbd> for keyboard input, <samp> for program output, and <var> for variables—each adds semantic meaning beyond just appearance.