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.
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) ". ";
}
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) ". ";
}
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) " ";
}
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) ". ";
}
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;
}
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! ❤️