How to Create Code Block in HTML: Simple Syntax and Examples
To create a code block in HTML, use the
tag to mark inline code and the tag to preserve formatting for blocks of code. Combine with to display multi-line code blocks with proper spacing and line breaks.
Syntax
The <code> tag is used to mark code snippets, usually inline. The <pre> tag preserves whitespace and line breaks, making it ideal for multi-line code blocks. Combining <pre> and <code> tags is the best way to show formatted code blocks.
html
<pre><code><pre>
<code>
// Your code here
</code>
</pre></code></pre>Output
<pre>
<code>
// Your code here
</code>
</pre>
Example
This example shows how to create a multi-line code block that keeps indentation and line breaks visible in the browser.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Code Block Example</title> </head> <body> <h2>Example of a Code Block</h2> <pre><code>function greet() { console.log('Hello, world!'); }</code></pre> </body> </html>
Output
Example of a Code Block
function greet() {
console.log('Hello, world!');
}
Common Pitfalls
One common mistake is using only the <code> tag for multi-line code, which does not preserve spaces or line breaks. Another is forgetting to use <pre>, causing the code to display as a single line. Also, avoid using deprecated tags like <tt> or inline styles for code blocks.
html
<!-- Wrong way: code tag alone --> <code>function greet() { console.log('Hello'); }</code> <!-- Right way: pre + code --> <pre><code>function greet() { console.log('Hello'); }</code></pre>
Output
Wrong way: function greet() { console.log('Hello'); }
Right way:
function greet() {
console.log('Hello');
}
Quick Reference
- <code>: Marks inline code snippets.
- <pre>: Preserves whitespace and line breaks for blocks.
- Combine
<pre>and<code>for multi-line code blocks. - Use semantic tags for accessibility and clarity.
Key Takeaways
Use
<pre> with <code> to create readable multi-line code blocks.<code> alone is for inline code and does not preserve formatting.Always include
lang and charset meta tags for proper HTML setup.Avoid deprecated tags and inline styles for code blocks to keep HTML semantic and accessible.
Preserving whitespace with
<pre> ensures code looks exactly as typed.