home Software Keep Text Formatting In HTML Using The pre Tag

Keep Text Formatting In HTML Using The pre Tag

While writing my OpenGL and Visual Studio Express 2008 article, I had a number of times where I wanted to include source code or error logs from the compiler. These are large sections of code that I want to display exactly as they printed out.

The problem with HTML, is that browsers will not render consecutive spaces, line breaks, and other information unless it is written as an HTML tag. So it doesn’t look the same as you typed it in. It won’t keep the text formatting in HTML.

I found a solution to the problem however…the pre tag. Just encapsulate your text with this and it will display exactly how you want it. Multiple spaces, new lines, and whatever else. The pre tag will preserve text formatting for you!

One problem I found is the the pre tag would not word wrap or line wrap by default. This can be fixed in your CSS style sheet for the page.

This link is where I found the solution: Forcing Long Text Lines To Wrap.

This is the code I added to my CSS file to make it work:

pre {
white-space: -moz-pre-wrap; /* Mozilla, supported since 1999 */
white-space: -pre-wrap; /* Opera 4 - 6 */
white-space: -o-pre-wrap; /* Opera 7 */
white-space: pre-wrap; /* CSS3 - Text module (Candidate Recommendation) http://www.w3.org/TR/css3-text/#white-space */
word-wrap: break-word; /* IE 5.5+ */

Try it out for yourself to see how well it works.

Leave a Reply