Normally HTML collapses spaces and line breaks. For code and fixed layouts you want them kept. That is what pre is for.
pre
pre means preformatted. The text is shown in a monospace font with spaces and new lines kept.
<pre>
Title Price
Slow Garden $14
River Notes $11
</pre>
code
code marks a piece of computer code. It is usually shown in a monospace font. Put it inside pre for multi-line code.
<p>Use the <code>href</code> attribute to set a link address.</p>
<pre><code>function greet(name) {
return "Hello, " + name;
}</code></pre>
Remember to write < and & inside code samples, as shown in HTML Entities.
kbd and samp
| Element | Use |
|---|---|
kbd | Keys the user presses |
samp | Output from a program |
var | A variable name |
<p>Press <kbd>Ctrl</kbd> + <kbd>S</kbd> to save.</p>
<p>The program prints <samp>File saved</samp>.</p>
Long lines in pre
pre does not wrap lines, so very long lines can run off the screen. A CSS overflow-x: auto; on the pre lets visitors scroll sideways.Exercise: show a key command
Write a sentence that tells readers to press Ctrl and C to copy, with the keys marked up as keys.
Show a possible solution
<p>Press <kbd>Ctrl</kbd> + <kbd>C</kbd> to copy.</p>