<code> and <pre>: Semantic Code Markup: A Quick Tip

Posted on Saturday, August 19th, 2006

I recently came across some problems whilst posting code on this blog. I was showing the javascript for my font sizing and stylesheet switching scripts and found that it was often awkward to format and display the code properly, even though I am using styled code tags around it.

The Problems

Indenting, line breaks… all the formatting that I had applied to make the code clearer to myself disappeared. Then I remembered the HTML element that retains that formatting; the <pre> (preformatted text) element. Using <pre> instead of <code> would make the script appear clearer and easier to understand. However, semantically the code element Designates a fragment of computer code. I want my markup to remain as meaningful as possible so what is the solution?

Solving the Problem

For a start, do not enclose pre elements inside code elements! I tried this and it causes all sorts of problems! The solution lies in CSS. The pre element is the only one to use the rare CSS attribute { white-space: pre; } as standard. Applying this rule to the code element as well, and using it to mark up computer code retains the meaning in your markup as well as the formatting. What could be simpler?

One thing though: watch out for long lines in your code, { white-space: pre; } doesn’t enforce natural line breaks so some code may spill over the edge of your layout. Sparing use of the <br> tag will fix that though, just make sure you indicate line breaks where they wouldn’t normally occur.

IE Spoils The Party

I couldn’t expect something this simple to work in IE though. If you have a paragraph with a code element inline, IE forgets that paragraphs do wrap as normal and stretches the rest of the paragraph across the page. Thankfully, if you are slipping a small piece of code into a a paragraph it is unlikely to be on two lines itself. All you need to do then, is create a class, “inline” for example, and apply the default white-space attribute to it as so:

code.inline {
white-space:normal;
}

Now any inline code segments will not break in IE and all the markup is semantically happy and formatted as you always intended it to be.

If you enjoyed this post, why not subscribe to Unintentionally Blank

Comments

Leave a Comment