Lesson 77 +10 XP

CSS Counters

CSS Counters

CSS can COUNT for you: numbered headings, sections, checklists, all automatic.

The two magic properties

  • counter-reset: create (or reset) a counter, usually with a value.
  • counter-increment: add 1 (or more) each time a rule matches.
  • counter() in content: reads the value.

Numbered headings

body {
  counter-reset: section;        /* create counter called section */
}
h2::before {
  counter-increment: section;    /* bump on each h2 */
  content: "Section " counter(section) ": ";
}

Result: "Section 1:", "Section 2:", "Section 3:"...

Start value & step

ol {
  counter-reset: item 5;         /* start at 5 */
  list-style: none;
}
li::before {
  counter-increment: item 2;     /* go up by 2 */
  content: counter(item) ". ";
}

Styled counters

counter() accepts a list-style type:

li::before {
  content: counter(chapter, upper-roman) ". ";
}

TL;DR

  • counter-reset names + starts a counter.
  • counter-increment bumps it.
  • content: counter(name) prints it.
  • Fully CSS: no JavaScript counters!
  • Great for auto-numbered sections and checklists.