White spaces don't ignored in pre tag

hd. picture hd. · Aug 9, 2011 · Viewed 7k times · Source

I have read that the 'pre' tag will collapse all white spaces and tabs into one space ,but it doesn't do so in for me.

why is it so? is it depended on web browser or i should do something more?

Answer

ghayes picture ghayes · Aug 9, 2011

From HTML 4.01 Specification

The PRE element tells visual user agents that the enclosed text is "preformatted". When handling preformatted text, visual user agents:

  • May leave white space intact.
  • May render text with a fixed-pitch font.
  • May disable automatic word wrap.
  • Must not disable bidirectional processing

PRE tags will leave white space as you have typed it. The purpose is just that. If you don't use a pre tag, standard HTML will collapse white space as you have written. Use PRE if you are interested in preserving white space, not collapsing it.

Here is an example in JSFiddle.

This will preserve white space:

 <pre>
    Spaces
     and more
      galore
 </pre>

This will collapse white space:

 <div>
   All
    together
     now
 </div>