0
0
HTMLmarkup~8 mins

Preformatted text in HTML - Performance & Optimization

Choose your learning style9 modes available
Performance: Preformatted text
LOW IMPACT
Using preformatted text affects the browser's layout and paint phases by preserving whitespace and line breaks, which can impact rendering speed especially with large blocks of text.
Displaying code or text with preserved whitespace and line breaks
HTML
<pre>Very long preformatted text block repeated many times...</pre>
Using the semantic <pre> element lets the browser optimize rendering for preformatted text and signals intent, reducing layout thrashing.
📈 Performance Gainsingle reflow and more stable layout, reducing CLS
Displaying code or text with preserved whitespace and line breaks
HTML
<div style="white-space: pre;">Very long preformatted text block repeated many times...</div>
Using a generic <div> with CSS white-space: pre on very large text causes more layout recalculations and paint cost because <div> is a block element without semantic meaning and may trigger more reflows.
📉 Performance Costtriggers multiple reflows and repaints for large content, increasing CLS risk
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
<div style="white-space: pre;">large text</div>1 nodeMultiple reflows if content changesHigh paint cost for large text[X] Bad
<pre>large text</pre>1 nodeSingle reflow on loadModerate paint cost, stable layout[OK] Good
Rendering Pipeline
The browser preserves whitespace and line breaks in the preformatted text during Style Calculation and Layout. This can increase Layout and Paint time if the content is large or changes dynamically.
Style Calculation
Layout
Paint
⚠️ BottleneckLayout
Core Web Vital Affected
CLS
Using preformatted text affects the browser's layout and paint phases by preserving whitespace and line breaks, which can impact rendering speed especially with large blocks of text.
Optimization Tips
1Use the <pre> element for preformatted text instead of styling generic elements.
2Avoid very large preformatted blocks to reduce layout and paint cost.
3Limit dynamic changes to preformatted text to prevent layout shifts.
Performance Quiz - 3 Questions
Test your performance knowledge
Which HTML element is best for displaying text that preserves whitespace and line breaks with better rendering performance?
A<div> with CSS white-space: pre
B<pre>
C<span>
D<p>
DevTools: Performance
How to check: Record a performance profile while loading or updating preformatted text. Look for Layout and Paint events related to the <pre> or styled <div> elements.
What to look for: Check if Layout events are frequent or long-running, and if Paint times are high. Stable <pre> blocks should show fewer layout recalculations.