Display element as preformatted text via CSS
Quickly preserve whitespace and line breaks in HTML by setting your CSS style to white-space: pre;
. This method mimics the behavior of the <pre>
tag.
Then, link the class="pre"
to your desired element:
For a consistent width of characters similar to a <pre>
tag, you can also specify a monospace font using font-family: monospace;
in your CSS:
Going the extra mile with preformatted text
Syntax highlighting using <code>
For specific lines or segments of code
within a text block, the <code>
tag can be employed to draw attention or emphasize your inline code:
Customize more with CSS to fetch you the desired stylings:
Handling the big stuff (long unwrapped text)
With text blocks that surpass the container boundaries, a useful trick to keep the formatting in check while simultaneously wrapping lines is white-space: pre-wrap;
:
Inline vs Block: The Final Showdown
Preformatted text usually goes along with block-level elements. Take note of this when applying CSS:
Without display: block;
, inline elements like <span>
may behave in unexpected ways.
When <pre>
isn't your first choice
Styling control with a <div>
Sometimes, you might need more control over your styles than the <pre>
tag provides. Here's when to ditch <pre>
and knock on the door of CSS:
- When
<pre>
doesn't support the custom fonts or other stylings you want. - If applying a specific color scheme or background image tickles your fancy.
- When the default margin and padding pussyfoot around your committed design plan.
The art of accessibility
Ensure to render your preformatted text accessible. Abide by the semantic HTML rules and don't forget to provide ARIA roles as necessary for screen readers to give the right context of your preformatted text.
Was this article helpful?