Using CSS to style a code listing

This article was first published on tjkdesign.com (01-01-2007).

Thanks to Philippe Wittenbergh, this solution is now wrapper-free (read this though).

The challenge:

In a hurry? Check the bottom of this page

The markup

I am using an ol (Ordered List) as I believe it is the most appropriate HTML element to use since we are dealing with a list of code lines for which order matters. The reward we get from using this semantic element is that it naturally handles the numbering of the lines for us, so there is no need to worry about deleting or adding a whole li (list item) later.

  1. <ol>
  2. <li><code>ol {background:#036 url(/img/gutter.gif) 2.3em 0 repeat-y;overflow:auto;font-family:"Courier New",Courier,mono;margin:0;padding:1em 0 1em 2.8em;color:#fff;width:90%}</code></li>
  3. <li><code>ol li {background:#ffc;font-size:small;}</code></li>
  4. <li><code>ol code {color:#036;}</code></li>
  5. </ol>

The CSS

After using white-space:pre and the proper whitespace and returns, the markup in the listing above produces the one below:

  1. ol { background:#036 url(/img/gutter.gif) 2.3em 0 repeat-y; overflow:auto; font-family:"Courier New",Courier,mono; margin:0; padding:1em 0 1em 2.8em; color:#fff; width:90%; }
  2. ol li { background:#ffc; font-size:small; }
  3. ol code {color:#036;}

Use this file if you wish to cut and paste the above rules.

white-space:pre causes whitespace to be treated as it is in the HTML element pre, with whitespace and returns fully preserved. Note that using this declaration can break the layout in Internet Explorer 5/6 if the content is too large for the container. You will need to wrap the ol in a DIV if you experience this behavior.

How things work

Everything is pretty much semantic, we insert the lines of code between CODE tags and then wrap them again inside li (List Items).

We use the background image as a mask to make sure we can add padding, or let the inner elements scroll horizontally, without revealing the ol's background color (dark blue) that creates the gutter. This is why we use a "repeat-y" value and set the x-axis to 2.3em. This is the background image.

On the CSS front:

Plugging a few span and attributes is all we need to make a listing look much nicer:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  3. <head>
  4. <title>How to style a Listing with CSS</title>
  5. <!--#include virtual="/inc/aBunchOfStuff.asp" -->
  6. <script type="text/javascript" src="/js/generic.js"></script>
  7. /* must not show on this page */
  8. <style type="text/css" media="screen">
  9. #logo {visibility:hidden}
  10. </style>
  11. </head>

Things to consider