A pre element preserves preformatted text; code marks computer code. Together they retain line breaks and indentation when those characters help a reader understand a command or snippet.
HTML pre and code: preserve source layout without hiding the meaning
Use the contract
An operations note records a small SQL query used to inspect delayed parcels. Put it in pre and code so the line breaks are stable when copied. Nearby prose explains the query's purpose and the account boundary; the snippet is not an instruction to run it against production without review. The HTML parser still processes markup characters inside code, so an embedded less-than sign must be escaped in the source document. A pre block also keeps long lines, which can overflow a narrow screen. Break a line deliberately where the language permits, or provide a readable scroll treatment in CSS.
<main>
<h1>Delayed parcel query</h1>
<p>Read-only query for records awaiting a handoff after the cutoff.</p>
<pre><code class="language-sql">SELECT parcel_id, depot_code
FROM dispatch_queue
WHERE handoff_hour < 17
ORDER BY parcel_id;</code></pre>
<p>Review query permissions before running it against live data.</p>
</main>Behavior and cost
The elements add no script or network request. Syntax highlighting is optional and often costs more than the markup, so keep the plain source readable first. A language class can help a highlighter or editor, but HTML itself does not highlight code. For command output, use the element whose semantics represent sample output rather than labeling it as a program. Test copy and paste, horizontal overflow at narrow widths, and screen-reader reading order. Keep credentials, private queries, and operational secrets out of examples; pre preserves text, it does not redact it.
Common Mistakes
- Do not paste raw markup delimiters into a code sample without escaping them.
- Do not force every note into pre when normal prose is clearer.
- Do not depend on highlighting to communicate the only difference between two code paths.
Connected lessons
- HTML inline text: emphasis, importance, code, and abbreviations
- HTML character references: escape data before inserting it into markup
- HTML wbr: suggest a break inside an unbroken identifier
Continue with HTML kbd, samp, and var: separate input, output, and variables.
