CSS counters – automatic numbering before h2

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 use counter-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>
refresh
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments