HTML: the code element
The <code> element marks a short fragment of computer code or a code-related name in text.
What you will learn
- How to mark a short code fragment with
<code> - How to combine
<code>with<pre>for multi-line code - How
<kbd>,<samp>, and<var>differ
Inline code
<p>Run <code>npm install</code> in the project folder.</p>
Use <code> when code appears within a sentence. It gives the fragment a programmatic meaning; CSS can control its font and color.
Multi-line code
<pre><code class="language-javascript">function greet(name) {
return `Hello, ${name}`;
}</code></pre>
<pre> preserves whitespace and line breaks. Combining it with <code> communicates that the preserved text is source code. A syntax-highlighting class can help visual readers, but it should not be the only way to understand the example.
Related text elements
<kbd>: input a user should type, such as Ctrl + S.<samp>: sample output from a computer program.<var>: a variable or placeholder value.
Common mistakes
- Using
<code>only for visual monospace styling when the text is not code. - Using repeated spaces in a paragraph instead of
<pre>for preserved formatting. - Using
<kbd>for program output or<samp>for user input. - Hiding important code information in syntax colors without a text explanation.