DEV Community

Cover image for Automatically counting and numbering HTML elements with CSS counters
Kelvin Wangonya
Kelvin Wangonya

Posted on • Originally published at wangonya.com

39 6

Automatically counting and numbering HTML elements with CSS counters

Say you had an unknown number of <div> elements and (for some reason) you wanted to count them and number each other them automatically - how would you do it? If you're like me, your first thought would be to use some kind of Javascript to play around with the DOM. What if I told you (insert Morpheus voice here) you can do it with CSS?

How to use CSS counters

Getting counters working requires three steps:

  • Initialize the counter with counter-reset
  • Increment the counter with counter-increment
  • Show the current counter value with counter()

It's pretty simple, really. The Pen below demonstrates how to count and number three <div> elements.

Where would this be useful?

I discovered CSS counters while looking for a way to number images on my blog posts. That's one place it would really come in handy. Here's a quick example:

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (2)

Collapse
 
pramodghuge profile image
Pramod Ghuge

Everyday you learn something new!

Collapse
 
zed_developer profile image
#ZedZed

had no idea this is awesome

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay