Creating sub-numbering in HTML and CSS

An overview

Sub numbering is the creation of numbered lists in the style of 1.1, 1.2, 1.3 etc. This is easily achieved in Microsoft Word and other document editors with a simple click of a few buttons ..... but not on the web. There is no simple code to achieve this in the web world.

The problem we faced

We came across this issue when needing to create some Terms and Conditions for a client in the sub-numbering style. We wanted a mechanism that if the client swapped sections or headers about, added in new points then it would automatically re-number the sections without it being a manual job ...... so we turned to a set of lesser known CSS commands which gives you the ability to count.

Our demo

I have created a 'pen' on codepen.io to help demonstrate the code we used to achieve the sub-numbering technigue. Please see below :

A brief code overview and explanation

The headers start the main numbering, this numbering then gets picked up by the following lists.
To get the headers to increment automatically, we first begin my setting the H2's to increment by running this css command : counter-increment: h2;. Then to display the numbers infront of the H2's we need to use the ':before' psuedo class on the H2 and output the counter. Here is a sample of that code : h2:before { content: counter(h2) '. '; }.

Next is to setup the lists, we first need to 'hide off' the autogenerated bullets or numbers, as we are creating and outputting these ourselves.

In simple terms we setup a counter to count the number of li's in out list, we then append the 'header count number' along with 'li count number' infront of the li itself by using the :before psuedo class as we did above. Here is a sample of that code: ol li:before { content: counter(h2)'.' counters(li-items, ".")' '; }. As you can see we have seperated the counters with a '.'.

Some of you may have noticed we have called two different types of counters, counter() and counters(), counters needs to be used if you have nested ol/ul's as the counter cascades through.

Counters can be setup to count pretty much anything you like, li's, headers, p's etc .... you can also add extra styling to the numbers that get generated, you can bold up just the numbers or change the colours of just the numbers .... which you can not do in standard HTML lists!

A perfect solution!

Comments