Nested List Counters with CSS

CSSCSSBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the use of CSS counters to create custom list counters. Specifically, we will learn how to initialize and increment counter variables, and how to display the value of these variables using the counters() function. By the end of this lab, you will be able to create nested list counters and customize the appearance of list elements using CSS.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL css(("`CSS`")) -.-> css/BasicConceptsGroup(["`Basic Concepts`"]) css(("`CSS`")) -.-> css/IntermediateStylingGroup(["`Intermediate Styling`"]) css/BasicConceptsGroup -.-> css/selectors("`Selectors`") css/IntermediateStylingGroup -.-> css/lists_and_tables("`Lists and Tables`") css/IntermediateStylingGroup -.-> css/pseudo_elements("`Pseudo-elements`") subgraph Lab Skills css/selectors -.-> lab-35184{{"`Nested List Counters with CSS`"}} css/lists_and_tables -.-> lab-35184{{"`Nested List Counters with CSS`"}} css/pseudo_elements -.-> lab-35184{{"`Nested List Counters with CSS`"}} end

Counter

index.html and style.css have already been provided in the VM.

To create a custom list counter that accounts for nested list elements, follow these steps:

  1. Use counter-reset to initialize a variable counter (default 0), with the name being the value of the attribute (e.g. counter).
  2. Use counter-increment on the variable counter for each countable element (e.g. each <li>).
  3. Use counters() to display the value of each variable counter as part of the content of the ::before pseudo-element for each countable element (e.g. each <li>). The second value passed to it ('.') acts as the delimiter for nested counters.

Here is an example HTML code:

<ul>
  <li>List item</li>
  <li>List item</li>
  <li>
    List item
    <ul>
      <li>List item</li>
      <li>List item</li>
      <li>List item</li>
    </ul>
  </li>
</ul>

And here is the CSS code to apply the custom list counter:

ul {
  counter-reset: counter;
  list-style: none;
}

li::before {
  counter-increment: counter;
  content: counters(counter, ".") " ";
}

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Counter lab. You can practice more labs in LabEx to improve your skills.

Other CSS Tutorials you may like