CSS and math? Yes, CSS can do some math too!

There is a very interesting methodology in CSS available to do custom incremental counting. At first, you may be thinking, of course, there is, we’ve all used ordered and unordered lists before. Well, that is true, the core idea has been in CSS for a while and we’ve all used it before. However, this is a bit different. This counter methodology, better known as counter incrementing, works on any element pretty much and can be reset anywhere. Now, let’s look at some code!

body {
  /* sets counter to 0 within the <body> element */
  counter-reset: heading-counter;
}

h1::before {
  /* Increment "my-sec-counter" by 1 */
  counter-increment: heading-counter;
  /*
    Increment by more/less than 1
    counter-increment: heading-counter +2;
    counter-increment: heading-counter -2;
  */
  content: "Chapter " counter(heading-counter);
}

Cool stuff if you ask me! Simple, yet powerful and extremely useful. Especially if you’re building out an application with a large amount of content.