<code>
A piece of computer code: the name of a variable, function, tag, or file, as well as a short listing.
- Display
- inline
- Closing tag
- Required
- Permitted content
- Phrasing content
Example
#<p>To print text to the console, use the <code>console.log()</code> function.</p>
<p>A page's main file is usually called <code>index.html</code>, and a paragraph is created by the <code><p></code> tag.</p>Definition and usage
#The <code> element marks a piece of code: the name of a variable, function, or tag, a file name, a command, or a short snippet of a program. Browsers display it in a monospace font.
Inside a sentence, plain <code> is enough. Put a multi-line listing in <pre><code>…</code></pre>, because <code> on its own collapses spaces and ignores line breaks, just like regular text.
Write the < and & characters as < and &, otherwise the browser will treat the sample HTML as real markup. The code’s language is conventionally given in a class with a language- prefix, e.g. class="language-js". Syntax-highlighting libraries rely on this convention.
Related elements are <kbd> (what the user types), <samp> (what the program responds with), and <var> (a variable in a formula or a placeholder symbol).
Syntax
#<code>code snippet</code>Attributes
#This element has no attributes of its own. It supports the global attributes, such as class, id and hidden.
More examples
#<pre><code class="language-python">for lesson in range(1, 4):
print("Lesson", lesson)</code></pre>Default CSS
#Most browsers display this element with these default styles:
code {
font-family: monospace;
}Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Remember the entities:
<instead of<and&instead of&. - A code block is
<pre><code>, a short inline fragment is plain<code>. - If the page highlights syntax, add a class with the language name, e.g.
language-css.
Related entries
#- <pre>Preformatted text: it preserves spaces, tabs, and line breaks exactly as they appear in the code.
- <kbd>Input entered by the user: keys, keyboard shortcuts, and commands to type.
- <samp>Sample output from a program: a message, a console response, or error text.
- <var>A variable in a math formula or a program, as well as a placeholder symbol in a command.
Spotted a mistake or missing an example? Write to us.