HTML Tutorial 0/139 lessons ~6 min read Lesson 32

    HTML Computercode

    html computercode code-related html elements mark programmatic text for assistive technology, copy computer code in html uses code, pre, kbd,

    Course progress0%
    Focus
    18 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Computer code in HTML uses code, pre, kbd, samp, and var to mark up programmatic text with correct semantics. Stripe API docs and Google developer guides wrap endpoints in code and multi-line samples in pre — screen readers switch pronunciation modes. Staff engineers never use pre for layout; syntax highlighting is CSS/JS on semantic markup.

    Business problem

    Code samples in div+monospace font lose copy semantics, break screen reader navigation, and exclude syntax highlighting pipelines. Amazon AWS docs migration to semantic pre/code improved accessibility audit scores and search within docs.

    • Developer experience: Wrong markup — copy button copies extra whitespace or loses line breaks.
    • A11y: Screen readers read unmarked monospace spans as prose — punctuation chaos.
    • SEO: Technical content in pre/code helps snippet extraction for dev queries.

    Why this feature exists

    Technical documentation needed elements distinguishing code from prose, user input from program output, and variables from literals — without relying on font-family alone.

    • code: Inline fragment — function name, attribute, file path.
    • pre: Preformatted block preserving whitespace — multi-line samples.
    • kbd/samp/var: Keyboard input, sample output, variable names respectively.

    Browser internals

    pre element has white-space: pre in user-agent CSS — preserves newlines and spaces. code inside pre is phrasing; pre cannot contain block elements. kbd defaults to monospace; nested kbd for key combos common pattern.

    • Overflow: Long pre lines overflow horizontally — wrap with CSS white-space: pre-wrap in design system.
    • Font: Monospace stack from UA — overridden by docs CSS.
    • Selection: Copy from pre preserves line breaks — critical for CLI samples.
    text
    inline: <code>fetch()</code> in paragraph
    block: <pre><code>const x = 1;
    console.log(x);</code></pre>
    kbd: <kbd>Ctrl</kbd>+<kbd>C</kbd>

    Rendering workflow

    Large pre blocks with syntax highlighting JS repaints on scroll if tokenization heavy — defer highlight library. Google Code Prettify replaced by build-time Shiki in static docs for zero client cost.

    • LCP: Giant pre above fold — text is LCP candidate; font subset for mono affects paint.
    • CLS: Highlight JS injects spans after paint — reserve min-height or SSR highlight.
    • Horizontal scroll: pre overflow-x auto — avoid layout expansion.

    Feature deep dive

    Patterns: Inline code for identifiers; pre>code for blocks (escape HTML entities in sample); kbd for shortcuts; samp for program output; var for mathematical or placeholder variables. Language hint via class on code (language-js) for highlighters — not official HTML attr except deprecated.

    • Escape: < and & in samples — always entity-encode angle brackets.
    • Line numbers: CSS counters or JS — don't fake with table layout for semantics.
    • Copy button: Reads textContent from code element inside pre.
    html
    <p>Install with <code>npm install @stripe/stripe-js</code>.</p>
    <pre><code class="language-js">const stripe = await loadStripe('pk_live_…');
    const { error } = await stripe.redirectToCheckout({ sessionId });
    if (error) console.error(error.message);</code></pre>
    <p>Press <kbd></kbd>+<kbd>K</kbd> to open search.</p>

    Accessibility analysis

    Screen readers may announce "code" or change voice for code elements — test NVDA with long pre blocks. Provide summary for very long samples. kbd elements help users hear "Ctrl plus C" correctly.

    • WCAG 1.3.1: Semantic code vs styled span — programmatic distinction.
    • Contrast: Syntax highlight token colors must meet contrast on code block background.
    • Focus: Copy button on pre must be keyboard operable with visible label.

    SEO impact

    Technical SEO for developer docs — code snippets matching query intent (curl examples, API paths) appear in featured snippets. Structured data TechArticle pairs with semantic code blocks.

    • Crawl: Code in pre is indexable text — API method names help relevance.
    • Duplicate: Same sample on 100 pages — thin content if no surrounding unique prose.
    • JSON-LD: SoftwareSourceCode schema optional for open source projects.

    Security considerations

    Code samples echoing user input — tutorial "try this" with unescaped user code in pre — XSS if reflected. Docs showing HTML examples must use entity encoding. CSP blocks inline script in copied samples if authors paste live script tags.

    • XSS: <script> in pre without escape — executes if outside pre context error.
    • Clickjacking: Fake CLI commands in UGC pre — social engineering vector.
    • Secrets: Accidentally published API keys in pre on docs site — scan in CI.

    Performance impact

    Stripe docs moved to build-time syntax highlight — zero client JS for code blocks on API reference pages. Reduces INP on long pages with 50+ samples.

    • DOM: Highlight adding 10 spans per line — 500 line pre — memory cost if client-side.
    • Fonts: Mono webfont for code — subset glyphs, font-display swap.
    • SSR: Pre rendered in HTML — good LCP text without JS.

    Real production example

    Google developer documentation — pre>code with language class, copy button, line wrap on mobile. Amazon AWS docs use tabbed code samples with semantic pre per language.

    • CMS: MDX compiles fenced code blocks to pre>code automatically.
    • lint: Ban bare pre without code child in design system.
    • Secrets: Redact keys in samples with obvious placeholder pattern.
    html
    <figure>
    <figcaption>cURL example</figcaption>
    <pre><code class="language-bash">curl https://api.stripe.com/v1/charges \
    -u sk_test_xxx:</code></pre>
    </figure>

    Enterprise usage

    Design system CodeBlock component wraps pre/code, provides copy, aria-label, and optional line highlight. Technical writers use MDX; CI checks entity escaping on HTML samples.

    • Style guide: kbd for UI shortcuts; samp for terminal output in tutorials.
    • i18n: Code usually LTR even in RTL pages — dir=ltr on pre.
    • Print: pre wraps for PDF export from HTML docs.

    Common production failures

    CMS "code block" inserted div with monospace class — copy broke line endings; accessibility audit flagged 200 pages. Migration to pre>code fixed in batch job.

    • XSS: User forum post in pre without sanitize — script in "example".
    • Perf: Client highlight on every page view — docs INP regression until SSR highlight.
    • Mobile: pre without overflow-x — horizontal page scroll — usability complaint.

    Architecture review questions

    • Are multi-line samples in pre>code with HTML entities escaped?
    • Is inline code used for short identifiers only — not whole paragraphs?
    • Do code block colors pass contrast requirements?
    • Are keyboard shortcuts marked with kbd elements?
    • Does copy functionality read from semantic code element?
    • Are secrets redacted from published code samples?

    Hands-on project

    Build a documentation code block component with pre/code, language class, copy button, SSR syntax highlight, mobile wrap, and axe audit on contrast.

    • Deliverable: Five sample blocks including bash and HTML escaped sample.
    • Verify: NVDA read-through of inline and block code.
    • Stretch: CI secret scanner on docs HTML output.

    Interview questions

    Why pre>code together instead of pre alone or div with monospace?(Advanced)

    pre preserves whitespace layout; code inside provides semantic 'this is code' for AT and indexing. div+font loses meaning. pre alone without code valid but code child is best practice for samples. Enables targeted CSS and copy selectors.

    Follow-up: Can pre contain other elements?

    How to syntax highlight without hurting LCP and INP on long docs pages?(Advanced)

    Build-time highlighting (Shiki, Prism at compile) embeds spans in SSR HTML — zero client cost. If client-side, highlight visible blocks only, use requestIdleCallback, avoid re-tokenize on scroll. Stripe docs pattern: static HTML highlight.

    Follow-up: What about line numbers for a11y?

    Security when displaying user-submitted code snippets in forums?(Advanced)

    Encode all HTML in text nodes inside pre/code; sanitize allowed tags only if rich; CSP blocks script execution; never reflect into innerHTML. Treat as text content. Amazon Q&A code in pre still encoded on output.

    Follow-up: Highlighting after encode?

    Try it yourself

    Edit the HTML, CSS, or JS panels — the preview updates as you type.

    Try it yourself

    Preview

    Summary

    Code-related HTML elements mark programmatic text for assistive technology, copy behavior, and documentation tooling. Production docs at Stripe and Google standardize on pre>code with build-time highlighting — styled divs are an accessibility and maintenance anti-pattern.

    Ready to mark this lesson complete?Track your journey across the entire course.