CSS - how to make numbering of all levels in nested lists

Asked

Viewed 141 times

1

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

By default lists only display the numbering of one 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 is thus:

1. item
  1.1. item
    1.1.1. item
    1.1.2. item
  1.2. item
2. item
  2.1. item
  2.2. item

1 answer

3


To do this it is necessary to use the function counters() of property content within CSS pseudo-element ::before of each item in the list. Source: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Counters.

Note 1: It is only possible to use a numbering type (e.g. decimal, Roman, letter) 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>

  • this is new for me! I didn’t even know what I had to do!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.