Tuesday

Automatically Numbering Non-Lists

CSS allows us to add incremented number counts to repeated items on a page. Very similar to an ordered list, where by simply using appropriate HTML markup (e.g. Ordered List Example), you'd sort of magically get your list items numbered in order from 1 to N. But, what if you want to number things that AREN'T a list. Well, step one might be to make those things into an ordered list, but sometimes you don't have that level of control, or semantics suggest something different.

As an example, perhaps you have yourself a site that has a group of articles (which is a new element in HTML5 - Note that articles aren't necessarily like a news article, but rather more like an article of clothing - that is, it is something stands uniquely on its own.); and let's say you want to number your articles in the order in which they appear on the page. Instead of manually adding something like "Article 1", "Article 2", and so on, you could instead just use CSS to help you out.

Essentially, what we can do is select the elements we want to number (in our case, just all "article" elements), and utilize the counter-increment property to define a CSS variable that will contain a number that will increment for each of elements of our selection that is found. Then, we just need to use that variable by utilizing the content property, and include our counter variable. Our CSS will look like this:

article { 
    counter-increment: articleCount;
}
article:before {
    content: "Article " counter(articleCount);
}
Basically, I have named our article counter-increment variable "articleCount", and then using the :before selector, adding my content. I'm first adding the string "Article " (note the space in there), and then add the counter, with my articleCount variable. Presto.

Notice that I'm also defining two unique sections, within which I have my articles grouped. I then added a similar, but separate sectionCount, so I could illustrate how the counter-increment is unique by parent node. That being said, you could opt to use the counter-reset property. You can also chain your counts together:

Full Demo with Code

Full Demo with Code (chained variables)

Usage

It's important to note that IE6/7 don't support this functionality; see here. Though, SitePoint also suggests buggy support in Opera, so something to look out for.

No comments:

Post a Comment