Nested counters and scope

Counters are "self-nesting", in the sense that re-using a counter in a child element automatically creates a new instance of the counter. This is important for situations like lists in HTML, where elements can be nested inside themselves to arbitrary depth. It would be impossible to define uniquely named counters for each level.

Example(s):

Thus, the following suffices to number nested list items. The result is very similar to that of setting 'display:list-item' and 'list-style: inside' on the LI element:

OL { counter-reset: item }
LI { display: block }
LI:before { content: counter(item) ". "; counter-increment: item }

The self-nesting is based on the principle that every element that has a 'counter-reset' for a counter X, creates a fresh counter X, the scope of which is the element, its preceding siblings, and all the descendants of the element and its preceding siblings.

In the example above, an OL will create a counter, and all children of the OL will refer to that counter.

If we denote by item[n] the nth instance of the "item" counter, and by "(" and ")" the beginning and end of a scope, then the following HTML fragment will use the indicated counters. (We assume the style sheet as given in the example above).


  1. item
  2. item

    1. item
    2. item
    3. item

      1. item




    4. item

  3. item
  4. item


  1. item
  2. item


The 'counters()' function generates a string composed of the values of all counters with the same name, separated by a given string.

Example(s):


The following style sheet numbers nested list items as "1", "1.1", "1.1.1", etc.

OL { counter-reset: item }
LI { display: block }
LI:before { content: counters(item, "."); counter-increment: item }