Counting With CSS Counters and CSS Grid

Thanks to Counting With CSS Counters and CSS Grid my attention was directed to this fact comes to using CSS Counters:

The effectiveness of counter() wanes when we realize that an element displaying the total count can only appear after all the elements to be counted in the source code. This is because the browser first needs the chance to count all the elements, before showing the total.

So how can one fix this? In said article the author resorts to CSS Grid Layout to position the counters visually above the stuff it’s counting.

.wrapper {
  display: grid;
  …
}

.counters { 
  grid-row: 1; /* places the counters on the first row */
  grid-column: 1 / 3;  /* ensures the counters span the full grid width, forcing other content below */
}

This trick can of course also be reproduced with Flexbox, by reordering the items using its order property.

.wrapper {
  display: flex;
  flex-direction: column;
  …
}

.counters { 
  order: 1; /* places the counters on the first row */
}

💁‍♂️ CSS Counters is one of the 9 Underutilized CSS Features

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

1 Comment

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.