Saturday, April 08, 2006

HTML : <pre><tt>y code

Well, in my first ever post to this blog I mentioned that I was trying to get the formatting to look good for my code examples. One of the easiest ways I found to do this in HTML was by using the <pre> tag. Any text between the <pre> and </pre> tags will not be formatted, i.e. wrapped or have whitespace stripped which your browser usually does. This is very handy for indented code.

One caveat is that you have to be careful to ensure the lines aren't too long. In this blog I ensure that a code line never exceeds column 67.

Ok, that takes care of the formatting, but how do I get a nice fixed width font for the code examples. Style-sheets! I hear you cry, and indeed they do come in very useful for exactly this kind of thing but there is a simpler way to achieve this common task in HTML, the <tt> tag. This stands for teletype. An easy-to-use tag it is much more suitable for writing code snippets in amongst the normal text. The alternative would be something like this: <div class="code"> and then you'd have to specify the styling, i.e. font etc. in a stylesheet - which, by the way, is the only place you should put style information - remember this simple rule:

HTML/XML = Content

CSS/XSL = Style

The two should always be seperate in any good system. Imagine having to go through every single one of your postings and changing them to conform to a style rather than simply changing the template and republishing!

Obviously you can still add additional styling for the <tt> tag if you wish. Indeed on this blog I have changed the font color slightly just to make the in place code snippets stand out a bit more.

I also enclose my large code examples in <blockquote>'s, which in my stylesheet/template is defined as having a darker background since this is how you'll find it done in most books written about code. Be careful to put the <blockquote> inside the <pre> and <tt> tags otherwise the darker blocks will extend to the top and bottom of the containing paragraphs and look ugly.

Anyway, if you have a blog of your own I hope this can help you have <pre><tt>ier text!

For a look at what a good stylesheet can do visit

1 comment:

Ressy said...

I've found that the under-utilized code, samp, and kbd tags are useful for this sort of thing, also-- instead of a div of class "code", just use a plain code tag and style it separately.

W3C: Phrase elements