Displaying a source code listing in two colors with <ol> and <pre>

This is in reply to an article on the css-d mailing list: Re: [css-d] How to nest font color changes?

View the source for horrendous code.

1. Solution with <ol>

This produces a real tag soup, but is an actual list. Also, every <li> contains at least one <code> element, because it is not allowed to wrap a block-level element in a <code> element. By the way, IE screws up the distance from the marker to the <li> content, but that's not the biggest problem. :-)

  1. this would be braces level 1 (no class) { this level 2 (class == even)
  2. still level 2 (class == even) { this level 3 (no class)
  3. } level 2 again (class == even) } level 1 again (no class)
  4. function myCoolFunction(Object oriented, String g)
  5. {
  6.    if (1 + 1 == 2)
  7.    {
  8.       /* Hello Whirl! */
  9.    }
  10. }

2. Solution with <pre>

In order to minimize the number of tags, <span>s –erm– span multiple lines, and as such coloring the line numbers as well. If you want to avoid that, you would either have to use a <span> around each line number, or terminate each span at the end of each line. Both options undo the size advantage this method has, compared to the <ol> approach.


01. this would be braces level 1 (no span) { this level 2 (span == even)
02. still level 2 (span == even) { this level 3 (no span)
03. } level 2 again (span == even) } level 1 again (no span)
04.
05. function myCoolFunction(Object oriented, String g)
06. {
07.    if (1 + 1 == 2)
08.    {
09.       /* Hello Whirl! */
10.    }
11. }

I think you can easily program it like this, presuming you start with numBraces (or whatever you call it) equal to 1: