Table of Contents
INTRODUCTION
The HTML <code> element is used to show a fragment of computer code on your webpage. It is an inline element
Display: By default, the text is shown by in the default monospace font of browser. This can be overridden by applying custom CSS.
The <code> element by itself only represents single line of code. When you want to show multiline code you can wrap <code> element inside <pre> element. The pre elements presents the text exactly as written in the HTML file preserving whitespaces and new line characters.
Syntax:
<code> --TEXT-- </code>
Example:
<code>
#include<stdio.h>
long long factorial(int n) {
if (n < 0) {
return -1;
}
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
</code>
Output: Using Only code Tag
#include
long long factorial(int n) {
if (n < 0) {
return -1;
}
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
Example: Using code Tag in Pre Tag
<pre>
<code>
#include<stdio.h>
long long factorial(int n) {
if (n < 0) {
return -1;
}
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
</code>
</pre>
Output:
#include<stdio.h>
long long factorial(int n) {
if (n < 0) {
return -1;
}
long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
Tag Omission
The HTML <code> element must have both start tag and end tag.
ATTRIBUTES
The <code> element only has global attributes.
Frequently Asked Questions (FAQ)
Why does code appear on one line in HTML, and how can I show it as multiline?
What is the difference between <code>, <pre>, and <samp> tags in HTML, and when should each be used for inline and block code snippets?
This tag is used for fragment of code. It is an inline element. Whitespace is Collapsed and line breaks or spaces is not preserved. It is used for Inline code snippets
<pre> - Preformatted text
This tag Preserves all whitespace, line breaks, tabs. It is a block element. It is used for displaying blocks of code, poetry, ASCII art, or anything where layout matters.
<samp> - Sample output
Represents program output, terminal responses, or messages shown to users. It is used for Showing output rather than input/code.