The <code> Element
As defined in the HTML Living Standard, the <code> element represents a fragment of computer code. This could be an XML element name, a filename, a computer program, or any other string that a computer would recognize.
The push() method adds one or more elements to the end of an array.
<p>The <code>push()</code> method adds elements to an array.</p>
View HTML Living Standard: The code element
Usage for Multi-line Code
To represent multiple lines of code, the <code> element should be wrapped in a <pre> element. The <pre> element preserves whitespace and formatting, while the <code> element provides the semantic meaning.
function greet(name) {
console.log("Hello, " + name + "!");
}
Accessibility Considerations
Using the <code> element ensures that the text is programmatically identifiable as code rather than standard prose.
WCAG Requirement: Info and Relationships
Success Criterion 1.3.1 (Level A): Information, structure, and relationships conveyed through presentation can be programmatically determined.
While many screen readers do not announce "start code" by default, using the semantic tag allows users to utilize specific screen reader settings to identify changes in font or style. It also provides a hook for browser extensions and user stylesheets to enhance the reading experience for users with cognitive or visual impairments.
Understand SC 1.3.1: Info and RelationshipsStyling Best Practices
- Monospace Font: Always use a monospace font family for
<code>elements to maintain user expectations. - Contrast: Ensure that the color of the code text (especially if using syntax highlighting) meets WCAG SC 1.4.3 contrast ratios against the background.
- Overflow: For long blocks of code, ensure the container has
overflow-x: autoto prevent layout breaking on small screens.