CSS Counters

CSS counters are a powerful feature that allows you to create custom numbering for list items and other content. They are especially useful for creating numbered lists, hierarchical lists, or any content where automatic numbering is desired.

Introduction to CSS Counters

CSS counters allow you to increment and display values that can be used for numbering items in a list or other content. They are defined using the `counter-reset` and `counter-increment` properties, and displayed using the `counter()`, `counters()`, and `counter-reset` functions.

Syntax


/* Define a counter */
counter-reset:  [];

/* Increment a counter */
counter-increment:  [];

/* Display the counter */
content: counter();

        

Examples

Basic Numbered List


/* Basic Numbered List */
ul {
    list-style-type: none;
    counter-reset: list-counter;
}

li {
    counter-increment: list-counter;
    position: relative;
    padding-left: 2rem;
}

li::before {
    content: counter(list-counter) ". ";
    position: absolute;
    left: 0;
    color: #333;
}

        
  • First item
  • Second item
  • Third item

Nested Lists


/* Nested Lists */
ul {
    list-style-type: none;
    counter-reset: main-counter;
}

li {
    counter-increment: main-counter;
    position: relative;
    padding-left: 2rem;
}

li::before {
    content: counter(main-counter) ". ";
    position: absolute;
    left: 0;
    color: #333;
}

ul ul {
    counter-reset: sub-counter;
}

ul ul li {
    counter-increment: sub-counter;
}

ul ul li::before {
    content: counter(main-counter) "." counter(sub-counter) " ";
    position: absolute;
    left: 0;
    color: #555;
}

        
  • Main item 1
    • Sub-item 1.1
    • Sub-item 1.2
  • Main item 2
    • Sub-item 2.1
    • Sub-item 2.2

Custom Numbering


/* Custom Numbering */
.custom-counter {
    counter-reset: custom-counter;
}

.custom-counter li {
    counter-increment: custom-counter;
    position: relative;
    padding-left: 2rem;
}

.custom-counter li::before {
    content: "Item " counter(custom-counter) ": ";
    position: absolute;
    left: 0;
    color: #007bff;
}

        
  • Custom item 1
  • Custom item 2
  • Custom item 3