<code>

Definition

The <code> element is a piece of inline <code> within a document. It is used to represent a fragment of computer <code>, and is typically rendered in a monospace font.

Examples

<!DOCTYPE html>
<html>
<head>
	<title>Code Demo</title>
</head>
<body>
	<p>Here is some code:</p>
	<code>
		var x = 1;
		var y = 2;
		console.log(x + y);
	</code>
</body>
</html>

In this example, the code is placed inside of the <code> element, which is nested inside of a <p> element. This will cause the code to be displayed as a block of preformatted text, with a monospace font and white space preserved.

Keep in mind, you can also use the <pre> element to display code blocks. The <pre> element preserves white space and line breaks, but does not display the text in a monospace font like the <code> element does. Here is an example of how to use the <pre> element to display a code block:

<!DOCTYPE html>
<html>
<head>
	<title>Code Demo</title>
</head>
<body>
	<p>Here is some code:</p>
	<pre>
		var x = 1;
		var y = 2;
		console.log(x + y);
	</pre>
</body>
</html>

In this alternate demo, the code is placed inside of the <pre> element, which is nested inside of a <p> element. This will cause the code to be displayed as a block of preformatted text, with white space preserved but not displayed in a monospace font.

Attributes

This element makes use of the global attributes.

Best Practices

  • Use <code> to represent a fragment of code, not an entire code block.
  • Use the <pre> and/or <code> elements together to represent a code block.
  • Avoid using the <code> element for other purposes, such as highlighting or emphasizing text.
  • Use the lang attribute to specify the language of the code fragment.
  • Use the dir attribute to specify the direction of the text within the code element.

Accessibility Considerations

Avoid using the <code> element for other purposes, such as highlighting or emphasizing text, as this can confuse assistive technologies.

Browser Compatibility

ChromeFirefoxSafariInternet ExplorerMicrosoft EdgeOpera
YesYesYesYesYesYes