How to change a span to look like a pre with CSS?
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:
Assign to your <span>
like so:
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:
Framing up with padding and borders
Include padding
and border
to add body and an outer shell to your <span>
, just like a <pre>
:
Managing bidirectional text
Apply unicode-bidi: embed;
if your content includes bidirectional text, as <pre>
sometimes has this by default:
Was this article helpful?