Apr
23
2009

How to Wrap Text within the <pre> Tag Using CSS

by   |  Posted in Tutorials  |  5 comments

I just came across an issue where I needed to make sure that the text within a <pre> tag wrapped. The default for this tag it to just let the text run on, no matter if the site’s page has ended. Not very good, if you ask me.

All you need to do is add this one pieces of code to your stylesheet and your text will wrap nicely.

pre {
  white-space: pre-wrap;       /* css-3 */
  white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
  white-space: -pre-wrap;      /* Opera 4-6 */
  white-space: -o-pre-wrap;    /* Opera 7 */
  word-wrap: break-word;       /* Internet Explorer 5.5+ */
}

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
If you liked this, please share it.

Tags: , , , , , , , , , , ,

Short URL: http://bit.ly/bR509F

Discussion 5 Comments

  1. Christopher Ross on April 28, 2009 at 1:35 pm

    That’s a really cool little trick Chris, thanks for posting it!

  2. Hmm on July 27, 2009 at 8:07 pm

    This makes validation of the CSS fail, getting following errors:

    Value Error : white-space
    -moz-pre-wrap is not a white-space value : -moz-pre-wrap

    Value Error : white-space -pre-wrap is
    not a white-space value : -pre-wrap

    Value Error : white-space -o-pre-wrap
    is not a white-space value :
    -o-pre-wrap

    Property word-wrap doesn’t exist :
    break-word

    • c.bavota on July 28, 2009 at 9:56 am

      The above will only be presented as an error in certain browsers. It is browser specific CSS to create a fix.

  3. Omid on November 15, 2009 at 11:01 am

    Very nice post, thank you a lot :*

  4. Bautagebuch on February 22, 2010 at 11:17 am

    Thx in advance! It is always a pleasure reading on bavotasan.com!