Implementing multi-level numbering using CSS counters

suggest change

CSS

ul {
  list-style: none;
  counter-reset: list-item-number; /* self nesting counter as name is same for all levels */
}
li {
  counter-increment: list-item-number;
}
li:before {
  content: counters(list-item-number, ".") " "; /* usage of counters() function means value of counters at all higher levels are combined before printing */
}

HTML

<ul>
  <li>Level 1
    <ul>
      <li>Level 1.1
        <ul>
          <li>Level 1.1.1</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Level 2
    <ul>
      <li>Level 2.1
        <ul>
          <li>Level 2.1.1</li>
          <li>Level 2.1.2</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Level 3</li>
</ul>

The example uses the self-nesting behavior of counters. When counter-reset reuses a name that is already in scope, it creates a new counter nested inside the existing one. Each nested ul therefore gets its own list-item-number for its child li elements, nested under the counter from the parent list.

The output is printed using the counters() function instead of the counter() function because the counters() function is designed to prefix the value of all higher level counters (parent) when printing the output.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents