Making Text in the HTML <PRE> Tag Wrap

After I installed Drupal and established this blog, I noticed that when I showed you a code snippet surrounded by a PRE tag the text in it would not wrap. Instead if it was wider than your screen you would have to scroll your browser horizontally. The solution was to use CSS to tell the browser to wrap text that is displayed within the PRE tag. In my stylesheet, I set the following for the PRE tag:

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;
}

I then loaded up my website and like magic the text now wraps! Thanks to Tero Karvinen for the CSS specific code posted on his website at http://users.tkk.fi/~tkarvine/pre-wrap-css3-mozilla-opera-ie.html.

Since some of you may be running Drupal and wondering where exactly I added this code, continue on reading. Within the Drupal stylesheet for my theme (bluemarine), I added the code above. Since I use the Drupal bluemarine theme, I updated the file named: /var/www/html/themes/bluemarine/style.css

The full style specified for the PRE tag in my Drupal stylesheet is now:

pre {
  background-color: #eee;
  padding: 0.75em 1.5em;
  font-size: 12px;
  border: 1px solid #ddd;
  /*TEA 04/07/07, below code added to make the PRE tag wrap.*/
  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;
}

Now this doesnt't seem to work as perfectly as I would like in IE, although it makes it better than it was. For me at least, in IE, there is still a little bit of a horizontal scroll bar when I have long text in a pre tag.

Hopefully this helps someone!



Comments

Fixing the Scroll Bar in IE

I figured out why the horizontal scroll bar shows up in Internet Explorer. My posts were being rendered within a table cell, and thus the PRE tags were also included in the cell.

In IE, it seems that we have to specify that the table-layout is fixed. So in your CSS specify the following:

width: 100%;
table-layout: fixed;

Or, put it inline in the table definition:

<table style="width: 100%; table-layout: fixed;">
v2.0