HTML <pre> Tag
Subject: html
HTML <pre>
Tag
The <pre>
(preformatted text) tag in HTML is used to display text exactly as it is written in the source code. Unlike <p>
or other inline tags, the <pre>
element preserves spaces, tabs, and line breaks, making it ideal for presenting formatted content such as code snippets, poetry, ASCII art, or any content where whitespace matters.
What Is the <pre>
Tag?
The <pre>
tag tells the browser to render the text as-isβmaintaining all line breaks and extra spaces. This is especially useful when presenting text that follows a specific format or layout.
Syntax:
Key Characteristics of <pre>
- Whitespace is preserved exactly as typed
- Displays in a monospaced (fixed-width) font by default
- Great for displaying code, log files, poems, or any structured text
- Block-level element (starts on a new line and spans full width)
Example β Basic Usage
Output: The text will appear exactly as written, maintaining all line breaks and indents.
Example β Displaying Code
When rendered in the browser, this appears in a clean, readable format, making it ideal for tutorials, documentation, and programming blogs.
Styling the <pre>
Tag with CSS
You can style the <pre>
tag like any other HTML element using CSS.
Example:
Important Notes
- By default,
<pre>
does not wrap text. If content is too long, it may overflow the container. - You can control this behavior with CSS:
- The default font is monospace, but it can be changed:
β
When to Use <pre>
Use the <pre>
tag when:
- You want to preserve line breaks, spaces, or tab spacing
- You're displaying code examples
- Showing terminal output, formatted logs, or ASCII text
- You need to maintain exact formatting from the HTML source
π« When Not to Use <pre>
Avoid using <pre>
:
- For regular paragraph text β use
<p>
instead - For layout design β use CSS with structural elements like
<div>
,<section>
, or<article>
- If you want automatic word-wrapping β since
<pre>
disables it by default
π Browser Support
The <pre>
tag is fully supported by all modern web browsers.
π Key Takeaway
The <pre>
tag is a simple yet powerful HTML element that allows developers to retain the formatting of their content. It plays a critical role in web development documentation, tutorials, and text-heavy formatting scenarios.
Use it when structure and spacing matter, and enhance it with CSS for better visual appeal and responsiveness.
Advertisement Slot 1
Advertisement Slot 2