How do I wrap text in a pre tag?
To enforce text wrapping in a <pre> tag, modify the CSS white-space property to pre-wrap:
You can also do this straight in your HTML:
This way, whitespace and line breaks are preserved, and text wraps to fit within its enclosing element.
Ensuring cross-browser compatibility
While the pre-wrap space-saving magic works for most modernized browsers, some time travelers (read: older browsers) may require a little coaxing.
- Mozilla: The
-moz-pre-wrap;fix is crucial for archaeological Mozilla browsers. - Opera: Versions 4-6 fancy
-pre-wrap;, whereas versions 7 and onwards prefer-o-pre-wrap;. - Internet Explorer: In the world of IE 5.5+, use
word-wrap: break-word;for a pleasant wrapping experience.
To keep all bases covered, you could apply:
Avoiding awkward mid-word line breaks
When enforcing text wrapping within <pre>, we may need to ensure breakpoints do not interrupt the flow of words:
- The
word-break: keep-all;style prevents line breaks from bisecting words in an unseemly manner.
Here's how to implement it:
Swapping pre for div - another useful trick
Switching out the <pre> tag for a <div> can help stave off horizontal scrolling on your page:
- Replace your
<pre>with a<div>but retain the whitespace formatting:
This maintains whitespace formatting while offering better layout control.
Defining a custom class for more control
If your page has varied <pre> tags each requiring distinct styles, using a custom CSS class can target specific adjustments:
Apply this class directly to your <pre> tags:
Balancing wrapping and readability
Pairing white-space: pre-wrap; with word-break: keep-all; can make your text within <pre> look clean and readable:
word-wrap: break-word;ensures breaks occur at whitespace instead of chopping words into pieces.white-space: pre-wrap;enables text to naturally wrap as the container resizes.
In CSS:
Was this article helpful?