138

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

Ben Rhys-Lewis
  • 3,118
  • 8
  • 34
  • 45
jsight
  • 27,819
  • 25
  • 107
  • 140

8 Answers8

202

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;
}
Dave F
  • 1,837
  • 15
  • 20
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
65

See the white-space CSS property.

.like-pre { white-space: pre; }
Pistos
  • 23,070
  • 14
  • 64
  • 77
  • 14
    alternatively, you may find `white-space: pre-wrap` useful. It behaves like `pre`, but wraps long lines. – Kai Carver Mar 31 '14 at 15:23
28

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.

Mr. Shiny and New 安宇
  • 13,822
  • 6
  • 44
  • 64
6

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

Sören Kuklau
  • 19,454
  • 7
  • 52
  • 86
5

while the accepted answer is indeed correct, if you want the text to wrap you should use:

white-space: pre-wrap;
Christophe Le Besnerais
  • 3,895
  • 3
  • 24
  • 44
3

Try this

span {
    white-space: pre;
    font-family: monospace;
    display: block;
    unicode-bidi: embed
}
Yanni
  • 2,583
  • 2
  • 20
  • 7
1

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/

josliber
  • 43,891
  • 12
  • 98
  • 133
Yesu Raj
  • 314
  • 3
  • 5
0

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.

  • 1
    Sometimes 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