CSS counters are variables maintained by CSS whose values may be incremented by CSS rules to track how many times they are used. Here is code flow on how css counters can be used to count h2 tags.
- Reset counter using
counter-reset: mycounter
. It can be done using body style. - Increment counter using
counter-increment: mycounter
on occurrence of an h2 tag. To increment value by more that 1, you can usecounter-increment: mycounter 2
. - Display counter using ::before and content property of h2 tag.
Example – counter to count and display h2 tags
<style> body { counter-reset: mycounter; } h2 { counter-increment: mycounter; } h2::before { content: counter(mycounter) ". "; } </style> <h2>First h2</h2> <h2>Second h2</h2> <h2>Third h2</h2>