CSS counters are, in essence, variables that are maintained by CSS and can be incremented using CSS rules to track how many times a certain element appears on a page. They are often used for things like creating automatic numbering on headings or item lists.
Here’s how you can use it:
1. First, you need to initialize the counter by using the counter-reset property. You can place this on any element that will encompass the elements you plan to count – often, this will be the body tag for counting things like headings or sections.
\`\`\`css body { counter-reset: section; } \`\`\`1. Next, you’ll increment the counter using the counter-increment. You’ll place this on the element that you are counting.
\`\`\`css h2 { counter-increment: section; } \`\`\`1. Finally, you utilize the counter by using the counter() or counters() function. This could be in a pseudo-element, often :before or :after. For example, to put the counter ahead of each h2:
\`\`\`css h2:before { content: “Section “ counter(section) “: “; } \`\`\`In this example, we’ve created a counter called ‘section’, incremented it for each h2, and then added the current counter number in content before each h2. So it will add “Section 1: “, “Section 2: “, “Section 3: “, and so forth before each h2 element.
But remember, for nested counters like the ones in nested lists you may need to use counters function which includes all the counters in a parent-child relationship:
``` li { counter-increment: item; position: relative; }
li:before { content: counters(item, “.”) “ “; position: absolute; left: -1.5em; } ``` In this example, each list item will be numbered by its hierarchy in the list — for example, “1.1.”, “1.2.”, “1.3.”, and so on.