Web Styles

CSS Counters

Automatic numbering, custom counters, and content generation.

Advertisement

CSS Counters

Automatic numbering, custom counters, and content generation.

Overview

CSS counters automatically number elements.

Key Concepts

  • counter-reset — Initialize a counter
  • counter-increment — Increment counter
  • counter() — Display counter value
  • counters() — Nested counters
  • content — Insert generated content

Code Examples

/* Ordered list with counters */
.list {
  counter-reset: item;
}

.list-item {
  counter-increment: item;
}

.list-item::before {
  content: counter(item) '. ';
  font-weight: bold;
}

/* Nested counters */
.nested-list {
  counter-reset: subitem;
}

.nested-list-item {
  counter-increment: subitem;
}

.nested-list-item::before {
  content: counter(item) '.' counter(subitem) ' ';
}

/* Roman numerals */
.roman-list {
  counter-reset: roman;
}

.roman-list-item {
  counter-increment: roman;
}

.roman-list-item::before {
  content: counter(roman, upper-roman) '. ';
}

/* Letters */
.letter-list {
  counter-reset: letter;
}

.letter-list-item {
  counter-increment: letter;
}

.letter-list-item::before {
  content: counter(letter, lower-alpha) ') ';
}

/* Complex numbering */
.article {
  counter-reset: section;
}

.article h2 {
  counter-increment: section;
}

.article h2::before {
  content: counter(section) '. ';
}

/* Step counter */
.steps {
  counter-reset: step;
}

.step {
  counter-increment: step;
  position: relative;
  padding-left: 60px;
}

.step::before {
  content: counter(step);
  position: absolute;
  left: 0;
  width: 40px;
  height: 40px;
  background: var(--primary);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

/* Invoice numbering */
.invoice-items {
  counter-reset: invoice;
}

.invoice-item {
  counter-increment: invoice;
}

.invoice-item::before {
  content: 'Item ' counter(invoice) ': ';
  font-weight: bold;
}

Practice

Build a step-by-step wizard with CSS counter numbering.

Advertisement