Is it possible to to change a <span>
tag (or <div>
) to preformat its contents like a <pre>
tag would using only CSS?

- 3,118
- 8
- 34
- 45

- 27,819
- 25
- 107
- 140
8 Answers
Look at the W3C CSS2.1 Default Style Sheet or the CSS2.2 Working Draft. Copy all the settings for PRE and put them into your own class.
pre {
display: block;
unicode-bidi: embed;
font-family: monospace;
white-space: pre;
}

- 1,837
- 15
- 20

- 112,730
- 33
- 157
- 176
-
3It's a good idea to do it this way in order to understand where these defaults come from. – Diodeus - James MacFarlane Oct 21 '08 at 15:07
-
2When I try this, the line breaks are not preserved. – Agnel Kurian Feb 19 '14 at 11:48
-
The – shindigo Jul 30 '14 at 13:19
-
1@shindigo Have you tried using `overflow: scroll`? Or if you only want horizontal scrolling `overflow-x: scroll` https://developer.mozilla.org/en-US/docs/Web/CSS/overflow – Kanmuri Sep 03 '14 at 17:06
-
1@shindigo ```overflow: auto;``` may be better otherwise you may end up with two sets of scrollbars when you don't need them. – Spechal Jun 28 '19 at 17:52
See the white-space CSS property.
.like-pre { white-space: pre; }

- 23,070
- 14
- 64
- 77
-
14alternatively, you may find `white-space: pre-wrap` useful. It behaves like `pre`, but wraps long lines. – Kai Carver Mar 31 '14 at 15:23
This makes a SPAN look like a PRE:
span {
white-space: pre;
font-family: monospace;
display: block;
}
Remember to change the css selector as appropriate.

- 13,822
- 6
- 44
- 64
Specifically, the property you're looking at is:
white-space: pre
http://www.quirksmode.org/css/whitespace.html
http://www.w3.org/TR/CSS21/text.html#white-space-prop

- 19,454
- 7
- 52
- 86
while the accepted answer is indeed correct, if you want the text to wrap you should use:
white-space: pre-wrap;

- 3,895
- 3
- 24
- 44
Try this
span {
white-space: pre;
font-family: monospace;
display: block;
unicode-bidi: embed
}

- 2,583
- 2
- 20
- 7
Try this style
.pre {
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
line-height: 1.5;
word-break: break-all;
white-space: pre;
white-space: pre\9; /* IE7+ */
display: block;
}
Used the same here - http://www.makemyshop.in/
Why not just use the <pre> tag, instead of the span tag? Both are inline, so both should behave in the way you would like. If you have a problem overriding the entire definition of <pre>, just give it a class/id.
-
1Sometimes you already have a span on a page and can't change it, like if it's part of an existing CMS system. – Mr. Shiny and New 安宇 Oct 20 '08 at 17:37
-
B/c the framework is refusing to put the contents under my
the way I'm asking it to. I could work around it, but that's a lot harder than just setting a few CSS props.
– jsight Oct 20 '08 at 18:04