Counting with CSS Counters

CSS counters are a powerful feature that allows you to create automatic numbering or counting systems for elements on a webpage. They provide a way to generate and display dynamic sequential values in your stylesheets.

Basics

Basic Counter Setup

Use the 'counter-reset' property to initialize a counter and 'counter-increment' to increment it.

				
					/* Initialize a counter named 'myCounter' */
body {
  counter-reset: myCounter;
}

/* Increment the 'myCounter' counter */
h2::before {
  counter-increment: myCounter;
  content: counter(myCounter) ". ";
}

				
			

Displaying Counters

Use the 'counter()' function to display the current value of a counter.

				
					/* Display the value of 'myCounter' before each paragraph */
p::before {
  content: counter(myCounter) ". ";
}

				
			

Intermediate Usage

Nested Counters

Create counters within counters for nested numbering.

				
					/* Nested counters for ordered lists */
ol {
  counter-reset: outerCounter;
}

li {
  list-style-type: none;
}

li::before {
  counter-increment: outerCounter;
  content: counter(outerCounter) ". ";
}

li li {
  counter-reset: innerCounter;
}

li li::before {
  counter-increment: innerCounter;
  content: counter(outerCounter) "." counter(innerCounter) " ";
}

				
			

Resetting Counters

Use 'counter-reset' to reset counters at specific points.

				
					/* Reset the counter at every section */
.section {
  counter-reset: myCounter;
}

.section h2::before {
  counter-increment: myCounter;
  content: counter(myCounter) ". ";
}

				
			

Advanced Techniques

Styling Counters

Style counters with CSS properties.

				
					/* Style the counter with custom colors and font size */
h2::before {
  counter-increment: myCounter;
  content: counter(myCounter) ". ";
  color: #3498db;
  font-size: 1.2em;
}

				
			

Using Counters for Generated Content

Apply counters to generated content like '::before' and '::after'.

				
					/* Use counters for generated content */
body {
  counter-reset: myCounter;
}

h2::before {
  counter-increment: myCounter;
  content: "[" counter(myCounter) "] ";
}

				
			

CSS counters are a valuable tool for creating dynamic and automated numbering systems in your web pages. From basic counter setup to advanced styling techniques, understanding how to leverage counters enhances your ability to create well-organized and visually appealing content. Happy Coding! ❤️

Table of Contents