When you have a growing list of things that have a complex format you may want to make them smaller when there are more of them. This UI-pattern is especially useful if the general overview is more important than the details of a specific item in the list. In the examples below we demonstrate a CSS-only technique that allows you to style elements based on their number.

Dear Santa, This year I'd like to have 100% support for all of CSS3 in all browsers. Cheers, the Digitpaint team

How does it work?

We can achieve the effect in CSS3 with the :first-child and :nth-last-child() pseudo-selectors. The :first-child selector does exactly what it says, it only matches the first child of an element. The :nth-last-child() is the inverse of :nth-child() ; this means it counts back from the last element. For example: :nth-last-child(2) would match the second to last element.

With that short explanation out of the way we can get to work. Say we want to style all <li> elements of an <ul> with exactly 4 <li> elements. First we select the first child with the li:first-child pseudo-selector. Next we only want the match the li:first-child if it's also the 4th last child with li:nth-last-child(4) . With the rule li:first-child:nth-last-child(4) we can style the first element if there are 4 elements in total. But we want to select the others too, so we have to match all other siblings with the sibbling-selector like this: li:first-child:nth-last-child(4) ~ li . Of course we have to combine the two rules to select them all:

li:first-child:nth-last-child(4), li:first-child:nth-last-child(4) ~ li{ .... styling ... }

Selecting X or more elements is quite easy to generate from this. Instead of only selecting :first-child:nth-last-child(4) we select :first-child:nth-last-child(n+4) .

Show us the source!

Feel free to look around the different source files we used for this example.