The <code>
tag is used to represent inline code within a document. It’s commonly used to display programming code or commands. It semantically indicates that the enclosed text is computer code, which is helpful for both users and search engines.
✅ Basic Syntax
<p>The <code>print()</code> function is used to output text in Python.</p>
📍 Result:
The word print()
will appear in a monospaced font (default browser styling for <code>
), distinguishing it as code.
📚 Common Use Cases
- Programming code: To display snippets of code within a block of text.
- Terminal commands: To show shell commands or CLI instructions.
- API methods or function names: To highlight functions like
getElementById()
orconsole.log()
.
🖥️ Example with Multiple Code Snippets
Here’s an example using the <code>
tag for inline code:
<p>To declare a variable in JavaScript, use <code>let x = 5;</code>.</p>
📍 Result:
The let x = 5;
will appear in a monospaced font, indicating that it’s a code snippet.
📑 Combining <code>
with <pre>
for Block Code
For longer code blocks, it’s best to use <pre>
(preformatted text) along with <code>
. This combination preserves whitespace and formatting.
<pre><code>
function helloWorld() {
console.log("Hello, World!");
}
</code></pre>
📍 Result:
The code will be displayed as a block, preserving indentation and line breaks.
🎨 Styling the <code>
Tag
You can easily style the <code>
tag using CSS:
<style>
code {
font-family: "Courier New", Courier, monospace;
background-color: #f4f4f4;
padding: 2px 4px;
border-radius: 4px;
}
</style>
<p>The <code>console.log()</code> function is often used for debugging.</p>
📌 Key Differences Between <code>
and <pre>
Tag | Use Case | Behavior |
---|---|---|
<code> | Inline code snippet | Displays code in monospaced font |
<pre> | Preformatted block of code | Maintains whitespace and line breaks (for blocks of code) |
<code> + <pre> | Long code block with formatting | Preserves both formatting and indentation |
✅ Summary
Feature | Description |
---|---|
Tag | <code> |
Purpose | Represents inline code |
Styling | By default: monospaced font |
Usage | Programming code, terminal commands, API functions |