What is the Pre Element?
The <pre> HTML element represents preformatted text that is to be presented exactly as written in the HTML file. When you wrap content in <pre> tags, the browser renders it in a monospace font and preserves all whitespace, including spaces, tabs, and line breaks.
How Pre Differs from Regular Text
In standard HTML, the browser performs whitespace normalization by default--it collapses multiple consecutive spaces into one and ignores line breaks, treating them as single spaces. The <pre> element bypasses this behavior entirely, giving you pixel-perfect control over text formatting that would be lost with standard HTML elements.
Key behaviors of the pre element:
- Monospace font rendering -- Text displays in a fixed-width font by default, ensuring all characters occupy equal horizontal space
- Whitespace preservation -- All spaces, tabs, and multiple consecutive whitespace characters remain intact
- Line break handling -- Line breaks from the source file are respected exactly, putting each new line on its own line
- Leading and trailing whitespace -- Indentation and spacing at the start and end of content is maintained
- Block-level display -- The pre element behaves as a block-level element, creating its own line before and after content
Use <pre> when precise text formatting is essential--code examples, terminal output, ASCII art, or any content where spacing carries meaning. For regular paragraph text, standard HTML elements remain the appropriate choice. When building accessible websites, understanding how preformatted text interacts with screen readers and assistive technologies is essential for creating inclusive web experiences.
Basic Syntax and Usage
The <pre> element is straightforward to use--wrap any content that requires preserved formatting inside the tags. The browser will render it in a monospace font with all whitespace intact.
Important syntax note: Browsers traditionally ignore the first newline character immediately after the opening <pre> tag. This prevents unwanted blank lines at the start of your preformatted content while maintaining readable source code.
Pre vs. non-pre rendering comparison:
Without <pre>, this content would appear as a single line: Line 1 Line 2 (with indentation) Line 3. With <pre>, each element gets its own line with exact indentation preserved.
The element accepts no specific attributes in modern HTML--styling and behavior are controlled entirely through CSS. This separation of concerns keeps your HTML semantic and your styling flexible, following modern web development best practices.
1<pre>2Line 13 Line 2 (with indentation)4Line 35</pre>Core Use Cases for Pre
The <pre> element serves several important purposes in web development. Understanding these use cases helps you apply the element appropriately and leverage its unique formatting capabilities.
Displaying Code Snippets
The most common use of <pre> in web development is displaying code examples, especially when teaching or documenting programming concepts. When combined with the <code> element, it creates an accessible and semantically meaningful way to present code. The preserved indentation and line breaks make code structure immediately visible to readers. This pattern is fundamental to technical documentation and developer-focused content.
ASCII Art and Text-Based Graphics
For retro-style graphics, diagrams, or visual elements created using characters, <pre> preserves the precise layout that makes these art forms work. Without <pre>, ASCII art would collapse into a single illegible line of characters. While ASCII art is less common in modern web design, it still appears in developer communities, command-line tool documentation, and retro-themed interfaces.
Preserving Data and Log Files
When displaying log outputs, error messages, terminal responses, or structured data, line breaks and spacing carry important meaning. Preformatted text lets users scan messages and understand hierarchies, sequences, and relationships that would be lost with standard text wrapping. This is particularly useful for debugging interfaces and monitoring dashboards.
Aligned Text and Tables
For simple label-value pairs or aligned data where spacing matters, <pre> provides a lightweight alternative to full table markup. This works well for configuration examples, file listings, or any structured text that benefits from character-level alignment without the overhead of full table markup.
Code Snippets
Display programming examples with exact indentation and structure preserved. Essential for documentation and tutorials.
ASCII Art
Present text-based graphics and diagrams that rely on character positioning for their visual meaning.
Data Display
Show log files, error messages, or structured data where line breaks and spacing carry important meaning.
Combining with Semantic Elements
The <pre> element works beautifully with related semantic elements designed for computer-related content. These combinations improve accessibility and SEO by clearly communicating the content's purpose to browsers, screen readers, and search engines.
The Code Element (<code>)
The <code> element marks inline code snippets. When combined with <pre>, it creates the standard pattern for displaying code blocks: <pre><code>...</code></pre>. The <code> element provides semantic meaning while <pre> handles formatting.
The Sample Element (<samp>)
The <samp> element represents sample output from a computer program, such as error messages, command responses, or system notifications. It signals to assistive technologies that this content is computer-generated output rather than user input or code.
The Keyboard Input Element (<kbd>)
The <kbd> element represents user input from a keyboard, voice command, or other input device. It's commonly used in documentation to show keyboard shortcuts and commands users should enter.
These semantic combinations create meaningful, accessible content that communicates the nature of computer-related text to all users. Following semantic HTML best practices ensures your code is both machine-readable and accessible to diverse audiences.
1<!-- Code example with pre and code -->2<pre><code>3function greet(name) {4 console.log("Hello, " + name);5}6</code></pre>7 8<!-- Sample output with pre and samp -->9<pre><samp>10$ npm install11added 142 packages in 3s12</samp></pre>13 14<!-- Keyboard input with kbd -->15<p>Press <kbd>Ctrl</kbd> + <kbd>C</kbd> to copy.</p>Accessibility Best Practices
Accessibility is critical when using <pre>, especially for visual content like ASCII art. Screen readers read preformatted content character by character, which can make ASCII art or structured data incomprehensible without context.
Providing Alternative Descriptions
People experiencing low vision and using assistive technology may not understand what preformatted text characters represent when read sequentially. Always provide alternative descriptions for ASCII art or diagrams created using preformatted text. This ensures all users can understand the content's purpose and meaning. Following web accessibility guidelines helps create inclusive experiences for all users.
Using ARIA Attributes and Roles
Combine <figure> and <figcaption> with ARIA attributes for accessible preformatted content. The role="img" attribute tells assistive technologies this is an image-like content, while aria-label provides a text alternative that describes what the ASCII art represents.
WCAG Compliance
Following W3C WCAG 2.0 Technique H86, provide text alternatives for ASCII art, emoticons, and leetspeak to ensure content is accessible to all users. This includes adding descriptive text that explains the visual content in words that screen readers can convey. Building accessible websites is a core part of modern web development services.
1<figure>2 <pre role="img" aria-label="ASCII COW">3 ___________________4 < I'm an expert in my field. >5 ---------------------------6 \ ^__^7 \ (oo)\\\_______8 (__)\\\ )\\/\\9 ||----w |10 || ||11 </pre>12 <figcaption id="cow-caption">13 A cow saying, "I'm an expert in my field." The cow is illustrated using preformatted text characters.14 </figcaption>15</figure>CSS Styling for Pre
While <pre> has default browser styles, you'll often want to customize its appearance to match your design system or improve readability. Modern styling approaches replace deprecated HTML attributes.
Font and Text Styles
Choose readable monospace fonts and establish consistent sizing. Stack multiple font families for cross-platform compatibility--starting with a specific web font like Fira Code, falling back to system monospace fonts. Proper line height improves code readability, and background colors help visually distinguish code blocks from surrounding content.
Responsive Considerations
The overflow-x: auto property prevents long lines from breaking page layout on small screens, enabling horizontal scrolling when needed. This approach maintains the exact formatting of preformatted content while keeping the page responsive. Following CSS best practices ensures consistent styling across browsers and devices.
Controlling Line Wrapping
Use the CSS white-space property for different behaviors: pre-wrap wraps long lines while preserving other formatting, while pre maintains exact spacing but may cause horizontal scrolling. Understanding CSS properties like these is fundamental to modern frontend development.
Dark Mode Support
Modern code displays often use dark backgrounds. Use the prefers-color-scheme media query to automatically adapt to user preference, providing a comfortable viewing experience in any lighting condition.
1pre {2 font-family: 'Fira Code', 'Consolas', monospace;3 font-size: 14px;4 line-height: 1.5;5 background-color: #f4f4f4;6 padding: 16px;7 border-radius: 4px;8 overflow-x: auto;9}10 11/* Wrap long lines instead of scrolling */12pre {13 white-space: pre-wrap;14}15 16/* Dark mode support */17@media (prefers-color-scheme: dark) {18 pre {19 background-color: #1e1e1e;20 color: #d4d4d4;21 }22}Common Mistakes to Avoid
Understanding common pitfalls helps you write cleaner, more accessible preformatted content and avoid rendering issues.
Not Escaping Special Characters
Since <pre> content is parsed as HTML, special characters like < and > need escaping. Without escaping, browsers interpret these as HTML tags, causing rendering errors. Always use < for less-than symbols and > for greater-than symbols.
Forgetting Accessibility
Never leave ASCII art or complex preformatted content without alternative descriptions. This excludes users relying on screen readers from understanding the content's purpose or meaning. Always provide descriptive text that conveys what the visual content represents.
Using Deprecated Attributes
The width and wrap attributes are deprecated in modern HTML. Use CSS properties like max-width, overflow, and white-space instead. This keeps your markup semantic and gives you more control over appearance. Following current HTML standards ensures your code remains future-proof.
Overusing Pre for Layout
Avoid <pre> for general page layout purposes. Reserve it for content that genuinely requires preserved formatting. For layout needs, use CSS Flexbox or Grid instead. Misusing <pre> for design purposes creates inaccessible, hard-to-maintain code.
1<!-- Wrong - unescaped characters -->2<pre><code>3if (a < b) {4 return true;5}6</code></pre>7 8<!-- Correct - escaped characters -->9<pre><code>10if (a < b) {11 return true;12}13</code></pre>Performance Considerations
Large <pre> blocks with extensive formatting can impact rendering performance. Following best practices helps maintain fast, responsive pages.
Rendering Performance
Preformatted content with many lines or complex indentation can slow down browser rendering. Use overflow-x: auto to prevent layout shifts that occur when content exceeds container width. Avoid extremely long <pre> blocks--break them into logical sections with headers to improve both performance and scannability.
Mobile Considerations
Ensure <pre> content is usable on mobile devices where horizontal space is limited. Smaller font sizes and appropriate padding prevent content from feeling cramped on narrow screens. Test your preformatted content on actual mobile devices to verify that horizontal scrolling works smoothly and users can access all content. Mobile optimization is a critical part of modern web development.
When to Consider Alternatives
For code examples longer than a few dozen lines, consider syntax highlighting libraries like Prism.js or Highlight.js that can lazy-load highlighting. These tools process content more efficiently and add features like line numbers and copy buttons that improve the user experience for code content.
Modern Alternatives and Enhancements
While <pre> handles the basics, modern development often uses additional tools to enhance code display with syntax highlighting, line numbers, and interactive features.
Syntax Highlighting Libraries
Syntax highlighters transform plain text into colorful, language-aware displays while maintaining accessibility. These libraries parse code and apply classes that CSS styles with appropriate colors for keywords, strings, comments, and other syntax elements. Implementing syntax highlighting is a common requirement in professional web development.
Copy-to-Clipboard Functionality
Add convenient copy buttons for code blocks to improve user experience. This small enhancement lets users quickly grab code examples without manually selecting and copying text, reducing friction in learning and implementation.
When to Use These Enhancements
For documentation sites, tutorials, and developer-focused content, syntax highlighting and copy buttons significantly improve the user experience. For simple use cases like displaying log output or configuration examples, plain <pre> remains the appropriate choice. Choose enhancements based on your content type and audience needs.
Prism.js
Lightweight and extensible with automatic language detection and over 100 themes
Highlight.js
Automatic language detection with support for 190+ languages and 250+ styles
Shiki
Uses TextMate grammars for VS Code-quality highlighting, rendered at build time
Best Practices Summary
- Always escape special characters (
<→<,>→>) - Combine with
<code>for semantic meaning when displaying code - Provide accessibility alternatives for visual content like ASCII art
- Use CSS for styling, not deprecated HTML attributes like
width - Consider syntax highlighting for code examples in documentation
- Test on mobile devices for horizontal scrolling behavior
- Use ARIA labels for complex preformatted content to aid screen readers
- Reserve for genuine formatting needs, not general layout purposes
Conclusion
The <pre> element remains essential for web development, providing precise control over text formatting that other HTML elements cannot match. Whether you're documenting code, displaying structured data, or creating text-based graphics, <pre> gives you the formatting control you need while maintaining the semantic structure that modern web development requires.
By following accessibility best practices, using semantic combinations with <code>, <samp>, and <kbd>, and leveraging CSS for styling, you can create well-formatted, accessible preformatted content that works across all devices and for all users.
Sources:
Frequently Asked Questions
What's the difference between <pre> and <code>?
<pre> preserves formatting (whitespace, line breaks) while <code> semantically marks text as code. Use them together: <pre><code>...</code></pre> for formatted code blocks.
How do I prevent horizontal scrolling in pre?
Use CSS white-space: pre-wrap to wrap long lines instead of scrolling, or set overflow-x: auto for controlled horizontal scrolling.
Do I need to escape characters in pre?
Yes! Since pre content is parsed as HTML, always escape < as < and > as > to prevent rendering issues.
How do I make pre accessible for screen readers?
Provide aria-label attributes describing the content, use role="img" for ASCII art, and consider wrapping in <figure> with <figcaption> for complex content.