CSS Pro-Tips

A list of some neat CSS tricks.

CSS Pro-Tips


Styling elements based on sibling count

Suppose you’d want to apply a different css rule depending on the number of siblings an element has, I.E. you want a column to have a 50% width if there’s two of it, 33.3% if there’s three and so on, without using any JS.

This code does the trick.

    { (insert col-1 css here) }

element:first-child:nth-last-child(2) ~ element
    { (insert col-2 css here) }

element:first-child:nth-last-child(3) ~ element
    { (insert col-3 css here) }

//and so on...

Here’s a working CodePen.

Credits to Lea Verou and André Luís.