25/4/05

Writing Blocks of Code

Filed under:
Web-design

You must have come accross a site where you wanted to insert a block of (X)HTML, CSS or some other code. Perhaps you run a blog and share some coding tips and tricks with the world, like me. What HTML tag(s) do you use to write your blocks of code? PRE, CODE, P, a combination of those, or something else? Are your blocks of code semantically correct?

In the Neighbourhood

I browsed through a few sites from my favorites folder, to see what methods other people use, and here I’ll mention just a couple…

Ordered lists

Roger Johansson from 456 Berea Street, as we can see, uses ordered lists. When indentation needs to be added, Roger simply applies a class with padding to a list item.

Styling a piece of code with CSS and using an ordered list may look pretty, but you have to admit, it really isn’t semantically correct. When you have tags like PRE and CODE, why use a list and create something that really isn’t a list?

Paragraphs

Douglas Bowman from Stop Design simply uses a paragraph and styles it with CSS. If indent needs to be added, he uses non-breaking spaces. Again, you have to wonder about the semantics behind this method.

Jeremy Keith on Adactio also uses paragraphs, followed by the CODE tag. For the indentation, he uses non-breaking spaces.

Is a block of code meant to be within a paragraph of text?

Thinking About the Semantics

Working on a new site made me and my friend Sulien think of the semantics behind it all. When asked about this issue, he was quick to suggest this:

<pre><code>...</code></pre>

Voila! We do need preformatted text, don’t we? And what we’re writing is computer code. Using the PRE tag will take care of the indentation problem, and no no-breaking spaces are needed, or line breaks, for that matter. So, pretty much everything works in our favour.

Your thoughts?

Comments: 4 responses to this post

  1. 1

    Yes, I agree. I use that method also.

    Šime Ramov on April 25, 2005

  2. 2

    Thanks, but I’m still waiting for XHTML2 and it’s BLOCKCODE element :) Ver.2 is semantic heaven in its ritchness…

    Sulien on April 26, 2005

  3. 3

    Maybe you should consider styling <code> elements with the white-space property, smtn like:
    <code style="white-space: pre;">...</code>
    This way you could avoid <pre> tags. I haven’t checked if this is supported by current browsers, though…

    maratz on April 27, 2005

  4. 4

    The white-space property is buggy, unfortunately.

    Bojan on April 27, 2005

Leave a comment

Web log categories

Previous blog post

Ljekarne Ricov

Next blog post

Musical baton