CSS Experiment: Centered Ordered List with List Content below its List Number

Wait. Why does a CSS article show up on a WordPress development blog?

Well first of all I stumbled upon this trick accidentally while developing this one theme I’m working on. And also I promise it will be short and simple enough. So do read on.

For the theme I want to display a Table of Content-style home page that will look like this (click the image to view full-size):

Centered ordered list with list content below its list number

That is a centered ordered list with list content below its number. The HTML structure I have is:

  <ol id="toc" class="clearfloat">       
    <li><h2><a href="#">I Learned that Adding an Egg to Ramen Soup is Awesome</a></h2></li> 
    <li><h2><a href="#">Why I believe printers are the spawn of Hell</a></h2></li> 
    <li><h2><a href="#">I nominate the most dangerous enemy ever created.</a></h2></li> 
  </ol>

…and so, the CSS.

This gets me curious because as we all know, list numbers normally show up to the left of the text. After a bunch of crazy experiments, some of which kept me puzzled about what really happened, I got this solution (leaving out the various text-formatting codes):

body {
  counter-reset: toc 0;  
  } 
 
#toc li:before {
  content: counter(toc, lower-roman) ".";
  counter-increment: toc;
  }  
 
#toc li {
  list-style-type: none; /* hide the numbers, show them via the toc li:before above */
  text-align: center;
  }

Here’s the main idea. I found out that if I use list-style-type:none and use generated content to display the numbers, the number will show up on top of the text. Great. Next we add text-align: center; and bam, everything is centered nicely as expected.

This is the first time I learned about counter-reset and counter-increment. They basically allow you to set the starting number on a list. I use 0 in my CSS so mine starts from 1, but that number can be anything. Here are some articles I found about this topic:

Results and Demo

Here’s a demo page for this CSS experiment. I’ve tested it and it works on Firefox 3.5, Opera 10, Chrome 3 and Safari 4. IE 8 doesn’t seem to support content, so it won’t show the generated number. I can live with that.

And that’s it. Hope it can be useful! I’ll release the theme pretty soon, so subscribe to the feed if you want to be updated.

You may also like...

2 Responses

  1. anima says:

    interesting, I’ve never seen anything like that before. definitely bookmarked!

css.php