Skip to navigation

malevolent design weblog

This blog is now defunct, but you can find more stuff over at my personal site

Finishing Touches: Code Blocks

Putting program listings into your site can be awkward. It isn’t obvious which tag(s) to use (<blockcode> is being introduced in XHTML 2.0), and long lines of code can easily break layouts or become illegible.

This site wraps blocks of code in <pre><code>…</code></pre>. <pre> is a block-level tag which displays white space and line-breaks within the source, <code> is an inline tag designed for marking up code. A dash of CSS lays it all out nicely in a box:

#content pre
	font-family:'andale mono','lucida console','courier new',monospace;
	margin:0 0 0.7em 0;
	padding:7px 10px 13px 10px;
	w\idth:473px; /*simplified box-model hack; ignored by IE5.x*/
	border:1px solid #cccccc;
	border-width:0 0 1px 1px;
#content code
	font-family:'andale mono','lucida console','courier new',monospace;

The overflow:auto bit produces a horizontal scrollbar for long lines. The rest will obviously vary for other layouts and you might not need a fixed width.

Alternatively, you could try wrapping long lines using this (found at Experts Exchange):

	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) */
	word-wrap: break-word;       /* IE 5.5+ */

I’ve not fully tested that, and wrapping lines of code can be very misleading, but might end up using it for my print style sheet (update: now added).


Comments are now closed for this entry.