CSS TutorialLesson #104

Nested Counters

You can create multiple counters for different levels of numbering. The following example creates one counter for the page (named "section") and one

CSS Using Two Counters

You can create multiple counters for different levels of numbering. The following example creates one counter for the page (named "section") and one counter for each <h1> element (named "subsection"):

Example

Example Code

css
Try it Yourself
body {
  counter-reset: section;
}

h1 {

counter-reset: subsection;
}

h1::before {
  counter-increment:
section;
  content: "Section " counter(section) ". ";

}

h2::before {

counter-increment: subsection;
  content:
counter(section) "." counter(subsection) " ";
}

The CSS counters() Function

The counters() function returns the current values of the named and nested counters, as a string.

Here we use the counters() function to insert a string between different levels of nested counters:

Example

Example Code

css
Try it Yourself
ol {
  counter-reset: section;

list-style-type: none;
}

li::before {
  counter-increment: section;

content: counters(section,".") " ";
}

CSS Counter Properties

PropertyDescription
contentUsed with the ::before and ::after pseudo-elements, to insert generated content
counter-incrementIncrements one or more counter values
counter-resetCreates or resets one or more counters
counter()Returns the current value of the named counter
counters()Returns the current values of the named and nested counters

Interactive Code Examples

CSS Example 1

css
Try it Yourself
Interactive runnable CSS example from EA Academy.
Live Output Preview:

CSS Example 2

css
Try it Yourself
Interactive runnable CSS example from EA Academy.
Live Output Preview: