The HTML Preformatted text tag, <pre>
, is used to define a block of text to display them in the same manner as it is written in the HTML file.
In HTML, we use the <pre>
tag to create preformatted text. For example,
<pre>
This Text will
be shown exactly
as it is written.
</pre>
Browser Output
![HTML Preformatted Text Text block inside an HTML](/sites/tutorial2program/files/html-pre.png)
The <pre>
tag preserves all new lines and white spaces. Hence, the above example shows the output exactly as it is written.
Font in HTML <pre> tag
By default, the HTML <pre>
tag changes the font of its content to a monospaced font. A monospace font is a font in which all the characters occupy the same space.
![HTML Preformatted Text Monospaced Font Default font in HTML](/sites/tutorial2program/files/html-pre-font.png)
As you can see in the above image, all the characters in the text have the same width.
Code in HTML <pre> tag
Generally speaking, the HTML <pre>
tag is used to include code block in our HTML pages. For example,
<pre>
let inviteFunction = async (invite) => {
let response = await fetch("/invite", {
method: "POST",
headers: getHeaders(),
body: JSON.stringify(invite),
});
let data = await response.json();
if (response.ok) return data;
throw new Error(data);
}
</pre>
Browser Output
![Code Sample in HTML Preformatted Text Block of Code written inside a HTML](/sites/tutorial2program/files/html-pre-code-sample.png)
Here we can see that using the HTML <pre>
tag is a great way to display code in our HTML articles. It preserves the white spaces, making code more readable.
In Contrast, if we use a <p>
tag, the output would appear as below.
<p>
let inviteFunction = async (invite) => {
let response = await fetch("/invite", {
method: "POST",
headers: getHeaders(),
body: JSON.stringify(invite),
});
let data = await response.json();
if (response.ok) return data;
throw new Error(data);
}
</p>
Browser Output
![Code Sample in HTML Paragraph Block of unformatted Code written inside a HTML](/sites/tutorial2program/files/html-pre-code-sample-in-paragraph.png)
Note: We also use the HTML <code>
tag to display code. To learn more visit HTML <code> tag.