CSS Ordered Lists with Counters

A couple of times in the past few weeks, people I know have expressed frustration with ordered lists in HTML.

In pure HTML, styling the numbers is a pain, as is breaking the sequence. However, there is a little known feature of CSS that allows us to generate our own numbers, meaning we can hide the HTML version with CSS and create our own as a :before or :after pseudo class, placing it and styling it however we want.

Here’s the CodePen example:

See the Pen Ordered Lists with CSS Counters by Alan Crissey (@TheRealAlan) on CodePen.

Counter

Using the counter is actually not one specific rule - it’s three. At the bare minimum, this is all you need:

ol {
  list-style: none;
  padding: 0;
  counter-reset: li; // Be sure to set this
}

li {
  margin: 0 0 10px;
  padding: 0 0 0 30px;
  position: relative;
}

li:before {
  content: counter(li); // Puts the count in as content
  counter-increment: li; // Attaches the 'li' tag to the counter
  display: inline-block;
}

Set a counter-reset: li; on the parent ol, and set the countent and counter-increment of the pseudo element of your list item. Easy.