HTML CSS Trick for Displaying Code Snippets: Wrap Long Lines with PRE Tag

The <pre> tag that defines preformatted text is the only tag in HTML that respects and preserves whitespaces like line-breaks, blanks, tabs and multiple spaces between words. Whatever is enclosed inside the pre element will be displayed as-it-is on the web browser.

The pre tag is therefore an excellent choice when you like to show a code snippet in your blog preserving the tabs and line breaks. Infact, most of the Adsense Javscript code snippets that you see on this blog are displayed using the PRE tag.

The only issue with pre tag in IE is that if the a particular line is too long, it could push the right sidebar (if you have any) to the bottom of the page. Firefox is immune to this but it will do extend the line into the sidebar without wrapping it.

Luckily, T. Longren has discovered a neat CSS hack to solve this pre text problem that will just wrap the long lines of code. All you have to do is insert the following code in the style element of your webpage or the external CSS stylesheet file if you have one.

pre {
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap !important; /* 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+ */
}


Your webpage layout will look as beautiful as before even with those lengthy lines of Javscript code and PHP scripts.

Wrapping Text Inside PRE Tags [Thanks, Lorelle VanFossen]