In HTML, code is often displayed using the <code>
and <pre>
elements. These tags are used to present computer code and ensure that it is displayed in a monospaced font, preserving formatting and indentation.
<code>
ElementThe <code>
element is used to display a short piece of code within a block of text. It is typically used within a <p>
or <li>
element to highlight code snippets:
<p>Use the printf()
function to display output.</p>
Use the printf()
function to display output.
<pre>
ElementThe <pre>
element is used to display preformatted text. It maintains whitespace and line breaks, making it ideal for displaying larger blocks of code:
<pre>
function helloWorld() {
console.log("Hello, world!");
}
helloWorld();
</pre>
function helloWorld() { console.log("Hello, world!"); } helloWorld();
<code>
and <pre>
To display a block of code with proper formatting and syntax highlighting, you can combine <pre>
with <code>
:
<pre>
<code>
function add(a, b) {
return a + b;
}
</code>
</pre>
function add(a, b) {
return a + b;
}
While HTML does not provide syntax highlighting for code, you can use CSS or JavaScript libraries to add color and style to code blocks. For example, using the PrismJS library:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/themes/prism.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/prism.min.js"></script>