Explain Codes LogoExplain Codes Logo

Display element as preformatted text via CSS

html
preformatted
css
accessibility
Nikita BarsukovbyNikita Barsukov·Aug 15, 2024
TLDR

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.

.pre { white-space: pre; }

Then, link the class="pre" to your desired element:

<div class="pre">Your preformatted content should be here.</div>

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:

.pre { white-space: pre; font-family: monospace; // Space, the "Final Font"-ier! }

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:

<p>Use the <code>console.log()</code> technique when debugging.</p>

Customize more with CSS to fetch you the desired stylings:

code { background-color: #f9f9f9; border: 1px solid #d1d1d1; padding: 2px 4px; border-radius: 3px; // Rounding the corners, because life isn't just about sharp edges! }

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;:

.pre-wrap { white-space: pre-wrap; overflow-wrap: break-word; // The text version of "Bend It Like Beckham". }

Inline vs Block: The Final Showdown

Preformatted text usually goes along with block-level elements. Take note of this when applying CSS:

.pre { white-space: pre; display: block; // Because everyone deserves a block party! }

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.