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.

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

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

element:first-child:nth-last-child(3),
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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s