4 min read
•Question 37 of 49mediumHow Do CSS Counters Work?
Understanding automatic numbering with CSS.
What You'll Learn
- Counter basics
- Nested counters
- Custom numbering
Basic Usage
styles.cssCSS
/* Initialize counter */
.list {
counter-reset: item;
}
/* Increment and display */
.list li::before {
counter-increment: item;
content: counter(item) ". ";
}Nested Counters
styles.cssCSS
ol {
counter-reset: section;
}
li::before {
counter-increment: section;
content: counters(section, ".") " ";
}
/* Result: 1, 1.1, 1.2, 2, 2.1 */Custom Styles
styles.cssCSS
li::before {
content: counter(item, upper-roman); /* I, II, III */
content: counter(item, lower-alpha); /* a, b, c */
content: counter(item, decimal-leading-zero); /* 01, 02 */
}Multiple Counters
styles.cssCSS
body {
counter-reset: chapter section;
}
h1::before {
counter-increment: chapter;
counter-reset: section;
content: "Chapter " counter(chapter) ": ";
}
h2::before {
counter-increment: section;
content: counter(chapter) "." counter(section) " ";
}