HTML Text Content & Typography Preformatted Text and Code Display in HTML

You paste some code into a paragraph tag. The browser collapses all your spaces, ignores your line breaks, and turns your nicely formatted snippet into one long, unreadable blob of text.

This is a real and frustrating problem when building tutorials, documentation pages, or any content that includes technical information. HTML has exactly the right tools to fix it.

In this tutorial, you’ll learn four HTML tags built specifically for technical content: <code>, <pre>, <kbd>, and <samp>. You’ll understand when to use each one, see them in action with real examples, and learn how to combine them to build proper HTML code display on any webpage.


01Why HTML Has Dedicated Tags for Technical Content

HTML treats all text the same way by default. It collapses multiple spaces into one, ignores tab characters, and throws away line breaks inside your tags. This is fine for paragraphs and headings, but it destroys code formatting completely.

On top of that, regular text elements carry no semantic meaning for technical content. A <p> tag around a JavaScript snippet just says “this is a paragraph.” It doesn’t say “this is code.” That distinction matters for browsers, search engines, and screen readers.

This is exactly what semantic HTML is about: using elements that communicate the meaning of your content, not just how it looks. The tags you’re about to learn do exactly that for technical content. They’re part of the broader family of HTML tags, elements, and attributes that give your content real structure and meaning.

The Whitespace Problem

❌ Inside a <p> tag

function greet() {
const name = “Daniyal”;
console.log(“Hello, ” + name);
}

✅ Inside a <pre> tag
function greet() {
    const name = "Daniyal";
    console.log("Hello, " + name);
}

This is the exact problem <pre> solves. But before we get there, let’s start with the most common one: the <code> tag.


02The HTML code Tag: Inline Code on Your Page

The <code> element marks up a short piece of code inline with your text. “Inline” means it sits right inside a sentence without jumping to a new line. It is an inline element, just like <em> or <strong>.

Browsers render it in a monospace font by default. This visually separates code from surrounding text, making it clear that the reader is looking at a technical value, not a regular word.

Basic Usage of the HTML <code> Tag

<!-- Inline code in a sentence -->
<p>To change the color of text, use the <code>color</code> property in CSS.</p>

<!-- File names -->
<p>Open the file called <code>index.html</code> in your editor.</p>

<!-- HTML tag names -->
<p>Use the <code>&lt;img&gt;</code> tag to add images to your page.</p>

<!-- JavaScript functions -->
<p>The <code>getElementById()</code> method selects an element by its ID.</p>

What to Use HTML Code Tags For

The <code> tag is the right choice for any of these:

  • HTML tag names mentioned in text, like <div> or <section>
  • CSS property or value names, like border-radius or flex
  • JavaScript function names, like querySelector() or fetch()
  • File names, like styles.css or package.json
  • Variable names or short one-line expressions
  • Terminal commands that fit in a single line

The key rule: if it’s short enough to fit naturally inside a sentence, use <code>. If it needs multiple lines, you’ll need <pre> as well. We’ll cover that combo shortly.

How <code> looks inside real text

To center an element, set its display property to flex, then add justify-content: center and align-items: center.

Open index.html in your editor. Inside the <head> section, link your stylesheet using the <link> tag. Then save and refresh to see your changes.

See how the code stands out from the regular text? That’s exactly what <code> is designed for. It’s subtle but clear.


03Preformatted Text in HTML with the pre Tag

The <pre> tag stands for “preformatted text.” Its whole job is to preserve whitespace exactly as you typed it in your HTML file: every space, every tab, every line break stays exactly where you put it.

Normal HTML ignores all of that. The HTML pre tag overrides that behavior and tells the browser: “Display this content exactly as-is.”

How the HTML Pre Tag Handles Whitespace

Here’s a simple demonstration. Take this text:

<!-- Without pre - spaces collapse, line breaks ignored -->
<p>
    Line one
    Line two
    Line three
</p>

<!-- With pre - everything is preserved -->
<pre>
    Line one
    Line two
    Line three
</pre>

The <p> version renders as a single line: “Line one Line two Line three.” The <pre> version displays each line on its own, with the indentation intact.

This is invaluable for code, poetry, ASCII art, file trees, or anything else where layout depends on spacing.

Displaying a Full Code Block with <pre>

<pre>
.container {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 16px;
    padding: 2rem;
}
</pre>

This renders the CSS exactly as written, with proper indentation and line breaks. No collapsing, no mess.

One important thing to know: <pre> is a block-level element. It starts on a new line and takes up the full available width, just like a paragraph or heading.


04Combining <pre> and <code> for Multi-Line Code Blocks

Here’s the most important pattern in this entire tutorial: when you need to display a multi-line code block, use both tags together. Wrap <code> inside <pre>.

Why both? <pre> handles the formatting (preserving whitespace). <code> handles the semantics (telling browsers this is code, not just preformatted text). Together, they give you the full package.

This is the standard pattern used everywhere on the web, from MDN documentation to Stack Overflow answers.

<!-- The standard pattern for code blocks -->
<pre><code>
function calculateArea(width, height) {
    return width * height;
}

const result = calculateArea(10, 5);
console.log(result); // 50
</code></pre>

Notice that </pre><code> has no space between the closing <pre> tag and the opening <code> tag. This prevents an extra blank line from appearing at the top of your code block in the browser.

Rendered Output Comparison

❌ <code> alone (multi-line)
function add(a, b) { return a + b; } const sum = add(3, 7); console.log(sum);
✅ <pre><code> together
function add(a, b) {
    return a + b;
}

const sum = add(3, 7);
console.log(sum); // 10

The difference is huge. Use <code> alone for inline snippets. Use <pre><code> together for every multi-line code block.


05The HTML kbd Tag: Keyboard Input

The <kbd> tag represents keyboard input. You use it when you’re telling a user which key or key combination to press.

The name “kbd” comes from “keyboard.” That’s a useful reminder: if you’re instructing a user to physically press something on their keyboard, <kbd> is the right tag.

By default, browsers render it in a monospace font, similar to <code>. But with CSS, you can style it to look like actual physical keys, which is far more intuitive for readers.

Basic Usage of the HTML <kbd> Tag

<!-- Single key -->
<p>Press <kbd>Enter</kbd> to submit the form.</p>

<!-- Key combination -->
<p>To save the file, press <kbd>Ctrl</kbd> + <kbd>S</kbd>.</p>

<!-- Sequence of keys -->
<p>Open the command palette with <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd>.</p>

Notice that each individual key gets its own <kbd> tag. The “+” between them is just plain text, not inside any tag. This is the correct approach.

Styling <kbd> to Look Like Real Keyboard Keys

The default browser styling for <kbd> is minimal. A few lines of CSS turn it into something that looks like actual keycaps, which helps users immediately recognize them as keyboard shortcuts.

<style>
kbd {
    background: #1e293b;
    color: #e2e8f0;
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-bottom: 3px solid rgba(255, 255, 255, 0.1);
    border-radius: 6px;
    padding: 4px 10px;
    font-family: monospace;
    font-size: 13px;
    font-weight: 600;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.4);
    display: inline-block;
}
</style>

<p>Open the integrated terminal with <kbd>Ctrl</kbd> + <kbd>&grave;</kbd></p>
Keyboard Shortcuts Using <kbd>
Save file
Ctrl+S
Copy
Ctrl+C
Undo
Ctrl+Z
Open DevTools
F12
Command palette (VS Code)
Ctrl+Shift+P
Open terminal (VS Code)
Ctrl+`

This is how every developer tool, documentation site, and tutorial should display keyboard shortcuts. It’s clear, recognizable, and immediately useful to the reader.


06The HTML samp Tag: Displaying Program Output

The <samp> tag is for displaying the output of a computer program, script, or command-line instruction. It represents what the computer says back to you.

Think of it as the pair to <kbd>. <kbd> shows what the user types in. <samp> shows what the computer prints out. Together, they tell a complete interactive story.

<!-- Basic samp usage -->
<p>When you run the script, you'll see: <samp>Build successful in 1.4s</samp></p>

<!-- Combining kbd and samp -->
<p>Type <kbd>node --version</kbd> and the terminal returns:</p>
<samp>v20.11.0</samp>

<!-- Multi-line program output using pre + samp -->
<pre><samp>
Compiling project...
Found 3 files
✓ main.js — OK
✓ utils.js — OK
✗ styles.css — Warning: unused selector
Build complete with 1 warning.
</samp></pre>

Just like with <code>, you can wrap <samp> inside <pre> when you need multi-line output to preserve its formatting.

Terminal — <kbd> and <samp> in action

~ $ 
node --version
v20.11.0
~ $ 
npm run build
Compiling project…
✓ main.js — compiled
✓ utils.js — compiled
⚠ styles.css — 1 unused selector
Build complete in 1.6s
~ $ 
node deploy.js
Error: Missing environment variable API_KEY

The terminal above uses <kbd> for commands the user types and <samp> for what the system outputs. The semantic difference is meaningful, and the visual result is clean and readable.


07A Quick Look at the <var> Tag

While we’re on the topic of technical HTML tags, there’s one more worth knowing: <var>. It represents a variable in code, math, or technical writing.

Browsers render it in italics by default. It’s a small but meaningful tag that completes the set.

<!-- Variable in a math context -->
<p>The formula is: <var>a</var>² + <var>b</var>² = <var>c</var>²</p>

<!-- Variable in a code context -->
<p>The function accepts <var>name</var> as its first argument.</p>

<!-- Variable in a command -->
<p>Run: <code>ssh <var>username</var>@<var>hostname</var></code></p>

You won’t use <var> in every article, but it’s a solid semantic choice when writing about mathematical formulas, function parameters, or command-line syntax where the user fills in their own values.


08Putting It All Together: A Technical Documentation Block

Now let’s see all four tags working together in a real-world scenario: a documentation block for a JavaScript function. This is the kind of content you’d find in any library’s official docs.

<section class="docs-entry">
    <h3>greet(<var>name</var>)</h3>
    <p>Logs a greeting to the console for the given <var>name</var>.
    Press <kbd>F12</kbd> to open DevTools and see the output.</p>

    <h4>Syntax</h4>
    <pre><code>greet(name)</code></pre>

    <h4>Example</h4>
    <pre><code>greet("Daniyal");
greet("World");</code></pre>

    <h4>Output</h4>
    <pre><samp>Hello, Daniyal!
Hello, World!</samp></pre>
</section>

greet(name)

Logs a personalized greeting to the console

Accepts a name string and logs a greeting message. Open DevTools by pressing F12 and go to the Console tab to see the output.

greet(name)
greet("Daniyal");
greet("World");
Hello, Daniyal!
Hello, World!

That’s a complete, properly semantic documentation entry. Every piece of technical content is wrapped in the tag that describes it best. This is how real documentation is built.


09How These HTML Tags Affect Your SEO

Using <code>, <pre>, <kbd>, and <samp> properly sends clear signals to search engines. When Google sees these tags, it understands that your page contains technical content. This helps your page rank for developer and programming-related searches.

On top of that, well-structured code display means users stay on your page longer. They can read your examples, understand your explanations, and actually learn something. Engagement time is a real factor in how search engines evaluate page quality.

Pair these tags with a solid heading structure and good paragraph formatting, and you have a page that’s both human-readable and search-engine-friendly from top to bottom.

Semantic code display is also a part of your overall HTML document structure. Every element you use purposefully adds to the quality signal your page sends to crawlers.


10Common Mistakes to Avoid

These tags are simple, but there are a few patterns that trip beginners up regularly.

🔧
Using <pre> for layout spacing
Some beginners use <pre> just to add blank lines or indent text visually. Don’t. It changes the font, disrupts your page’s semantics, and breaks accessibility. Use CSS for spacing.
🔧
Forgetting to escape HTML inside <code>
If you want to display an HTML tag like <div> inside a <code> block, you must write it as &lt;div&gt;. Otherwise the browser reads it as real HTML and hides it.
🔧
Using <code> alone for multi-line blocks
<code> doesn’t preserve whitespace on its own. For any code that spans more than one line, always wrap it in <pre><code>. Using <code> alone will collapse the formatting.
🔧
Putting multiple keys in one <kbd>
Writing <kbd>Ctrl+S</kbd> as one block is incorrect. Each key gets its own <kbd> tag. The “+” between them is plain text. This is both semantically correct and easier to style.
🔧
Using <div> or <span> for code
Using a generic <div> or <span> with a class like class="code" misses the whole point. The semantic tag is the meaning. Syntax highlighters, screen readers, and search engines rely on the actual tag name.
🔧
Mixing up <kbd> and <samp>
<kbd> is for what the user types in. <samp> is for what the computer outputs. They look similar by default, so beginners often mix them up. Keep the distinction clear in your writing.

11Quick Reference: All Four Tags at a Glance

<code>
Inline code
Marks short code snippets within flowing text. Renders in monospace font. Use it alone for inline content.
Example
Use <code>color</code> in CSS.
Best for
  • CSS properties & HTML tags
  • File and function names
  • Single-line snippets
<pre>
Preformatted text
Preserves every space, tab, and line break. Essential for multi-line code blocks. Combine with <code> for best results.
Example
<pre><code>…</code></pre>
Best for
  • Multi-line code blocks
  • ASCII art, file trees
  • Formatted output
<kbd>
Keyboard input
Represents keys or shortcuts the user presses. Each key gets its own tag. Style with CSS to look like real keycaps.
Example
<kbd>Ctrl</kbd> + <kbd>S</kbd>
Best for
  • Keyboard shortcuts
  • Key press instructions
  • Terminal commands typed
<samp>
Program output
Displays output returned by a program, script, or terminal. The complement to <kbd>. Wrap in <pre> for multi-line output.
Example
<samp>Build complete.</samp>
Best for
  • Terminal output
  • Error messages shown
  • Script return values

12What You Learned Today

You now have a solid understanding of how HTML handles technical content. To recap what you covered:

<code> is for inline code snippets within sentences. <pre> is for preformatted text that needs to preserve whitespace, and it’s used together with <code> for multi-line code blocks. <kbd> is for keyboard input and shortcuts. <samp> is for program output. And <var> is for variables in code and math.

These aren’t just styling tricks. They’re part of writing clean, semantic HTML that’s accessible, SEO-friendly, and easy to maintain. Every tag you use purposefully makes your content better for everyone who reads it, whether that’s a person, a screen reader, or a search engine crawler.

If you haven’t already, check out our guides on HTML text formatting and quotations in HTML to keep building your understanding of semantic text elements. The pattern is the same: the right tag for the right meaning.

Now go use these tags in your next tutorial, documentation page, or technical article. The more you use them, the more natural they feel.

Preformatted Text and Code Display in HTML

Choose a difficulty to load your challenge

Loading challenge…

Ready to Practice?

Select a difficulty level above to load your challenge.

Easy

1
Live Preview
Great Work!