<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
On this page

Example

#
HTML
<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>&lt;p&gt;</code> tag.</p>
Preview

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 &lt; and &amp;, 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

#
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

#
A code block with the language marked
HTML
<pre><code class="language-python">for lesson in range(1, 4):
    print("Lesson", lesson)</code></pre>
Preview

Default CSS

#

Most browsers display this element with these default styles:

CSS
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: &lt; instead of < and &amp; 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

#

Spotted a mistake or missing an example? Write to us.