HTML <pre> pre tag
The <pre>
tag in HTML is used to display preformatted text. Text within a <pre>
element is displayed exactly as it appears in the HTML code, including spaces, line breaks, and other whitespace. This is useful for displaying code snippets, text with specific formatting, or ASCII art where preserving the exact formatting is important.
Key Features:
- Preserved Formatting: The
<pre>
tag maintains whitespace, line breaks, and other formatting exactly as it is in the HTML code. - Monospace Font: By default, text inside a
<pre>
tag is displayed using a monospace (fixed-width) font, which aligns text vertically and horizontally in a grid-like structure.
Basic Syntax:
<pre>
This is a block of preformatted text.
Whitespace, including line breaks and spaces,
is preserved exactly as written in the HTML.
</pre>
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Preformatted Text Example</title>
</head>
<body>
<pre>
Here is some preformatted text:
- It maintains whitespace
- Line breaks are preserved
- Text is displayed in a monospace font
</pre>
</body>
</html>
In this example, the text inside the <pre>
tag is displayed exactly as written, including the indentation and line breaks.
Use Cases:
- Code Display: Commonly used to display code snippets, where maintaining the exact formatting and indentation is crucial for readability.
- ASCII Art: Useful for displaying ASCII art or other types of text-based graphics that rely on precise spacing and alignment.
- Formatted Text: When you need to show text that requires specific formatting, such as structured data or text that includes multiple spaces.
Styling:
You can style the <pre>
element with CSS to modify its appearance, such as changing the font, text color, or background.
pre {
font-family: "Courier New", Courier, monospace;
background-color: #f4f4f4;
border: 1px solid #ddd;
padding: 10px;
overflow-x: auto; /* Adds horizontal scroll if content overflows */
}
In this example:
- The font is set to a monospace font for better readability of preformatted text.
- A light gray background color and border are added for visual distinction.
- Padding is used to provide space around the text.
- Horizontal scrolling is enabled if the text overflows the width of its container.
Key Points:
- Preserves Formatting: The
<pre>
tag is ideal for text that requires exact formatting, such as code or structured text. - Monospace Font: By default, text inside
<pre>
is displayed in a monospace font. - CSS Styling: Can be customized with CSS for different visual effects and styling.
In summary, the <pre>
tag is a useful HTML element for displaying preformatted text where preserving the exact spacing, line breaks, and formatting is important. It is commonly used for code snippets and other text that benefits from a fixed-width font and precise layout.