07 Aug 2012 Getting OL numbers to display three digits and no dot.

As some of you may know, achieving ol numeration style similar to the one used here (i.e. always display three digits and no dot) is not as obvious as one might think.

Of course, we need to use custom css list counter for this and so we'll do it. Let's start by removing the dot, it's still fairly easy.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
ol {
    margin: 0;
    padding: 0;
    list-style: none;
    counter-reset: item;
}
ol li:before {
    counter-increment: item;
    content: counter(item) " ";
}

But then, how to force it to display the leading zeros? There comes the tricky part. I decided to do it this way.

Firstly, server-side preprocess the html, adding appropriate css classes for two leading zeros, one leading zero or no leading zeros (ten is for [less than] ten, hun for hundred and tou for thousand):

1
2
3
4
5
6
7
8
classify = (code) ->
    ol = ['<ol>']
    get_class = (i) ->
        return i < 9 and 'ten' or (i < 99 and 'hun' or 'tou')
    for line, i in code.split '\n'
        ol.push "<li class='#{get_class i}'>#{line}</li>"
    ol.push '</ol>'
    return ol.join ''

My actual code looks a bit different, because I'm doing this while highlighting at the same time, but it's irrelevant here.

Secondly, css side, we have to add a "conditional counter", based on our just specified classes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
ol {
    margin: 0;
    padding: 0;
    list-style: none;
    counter-reset: item;
}
ol li:before {
    counter-increment: item;
}
ol .ten:before {
    content: "00" counter(item) " ";
}
ol .hun:before {
    content: "0" counter(item) " ";
}
ol .tou:before {
    content: counter(item) " ";
}

I know it's not very general solution (what if a wanted four digits? five? six? Here comes the mess), but is enough for my needs.

One might possibly code a generator for the stylesheet, shouldn't be much trouble.