Explain Codes LogoExplain Codes Logo

How to change a span to look like a pre with CSS?

html
css
responsive-design
best-practices
Alex KataevbyAlex Kataev·Jan 14, 2025
TLDR

Transform a <span> to resemble a <pre> by setting white-space: pre;, which makes it respect whitespace and newline characters. Use display: block; so it gets its own line, in the style of a <pre>. Here's the distilled version:

span.fake-pre { white-space: pre; display: block; font-family: monospace; }

Assign to your <span> like so:

<span class="fake-pre">Your formatted content.</span>

By implementing these styles, you clone the <pre> formatting onto a <span> tag, neatly sidestepping any HTML semantics concerns.

Deep dive into 'pre'-tifying

To mimic the <pre> element, it's crucial to study its core styles, which are defined in the W3C CSS2.1 Default Style Sheet and the CSS2.2 Working Draft.

<pre> behavior demystified

The <pre> tag diligently protects spaces and newline characters thanks to the white-space property set as pre.

Going monospace

The font-family: monospace; style is typical for <pre> as it treats every glyph equally, allocating the same horizontal space for consistency.

Playing the block game

A block-level display makes your <span> act like a <pre>. This changes <span> from the default inline display to preserve text formatting within its own element box.

Advanced adjustments and refinements

Tackling content overflow

If your block-level element overflows the horizontal boundary, overflow: auto; or overflow: scroll; can come to your rescue:

.fake-pre { overflow: auto; /* So you ate too much? */ }

Framing up with padding and borders

Include padding and border to add body and an outer shell to your <span>, just like a <pre>:

.fake-pre { border: 1px solid #ccc; /* Make it pop! */ padding: 10px; /* The more the merrier! */ }

Managing bidirectional text

Apply unicode-bidi: embed; if your content includes bidirectional text, as <pre> sometimes has this by default:

.fake-pre { unicode-bidi: embed; /* I read right as well as left! */ }