CSS - how to do all-level numbering in nested lists

1

How to make nested list numbering include parent element numbers (all levels) using only CSS?

By default the lists only display the numbering of a level:

<ol>
  <li>item
    <ol>
      <li>item
        <ol>
          <li>item</li>
          <li>item</li>
        </ol>
      </li>
      <li>item</li>
    </ol>
  </li>
  <li>item
    <ol>
      <li>item</li>
      <li>item</li>
    </ol>
  </li>
</ol>

The expected result looks like this:

1. item
  1.1. item
    1.1.1. item
    1.1.2. item
  1.2. item
2. item
  2.1. item
  2.2. item
    
asked by anonymous 27.08.2015 / 19:24

1 answer

3

To do this you need to use the counters() function of the content property within the CSS% pseudo-element of each list item. Source: link .

Note 1: It is only possible to use a numbering type (eg decimals, roman, letters) for all levels, and it is not possible to mix two or more types.

Note 2: When selecting and copying the list, the numbers will not be copied, only the texts.

ol {
  /* zera contador para cada lista */
  counter-reset: item;
  /* remove estilo de lista padrão */
  list-style-type: none;
}
li::before {
  /* incrementa só o contador da lista atual */
  counter-increment: item;
  /* adiciona o valor de todos os contadores pai
  separados pelo segundo parâmetro */
  content: counters(item,'.') '. ';
  /* para suporte a IE < 8 não pode haver espaço entre os argumentos */
}
<ol>
  <li>item
    <ol>
      <li>item
        <ol>
          <li>item</li>
          <li>item</li>
        </ol>
      </li>
      <li>item</li>
    </ol>
  </li>
  <li>item
    <ol>
      <li>item</li>
      <li>item</li>
    </ol>
  </li>
</ol>
    
27.08.2015 / 19:24