Last Updated: February 25, 2016
·
1.627K
· benorudolf

Conditional styling of elements

There is a way to style sibling elements based on their number.

HTML

<div class="parent">
    <div class="siblings"></div>
    <div class="siblings"></div>
    <div class="siblings"></div>
    <div class="siblings"></div>
    <div class="siblings"></div>
</div>

[1] Styles apply if there is a precise number of sibling elements

CSS

.siblings { background: red; }

.siblings:first-child:nth-last-child(3),
.siblings:first-child:nth-last-child(3) ~ .siblings { background: green; }

Here, the siblings will become green, if there are only 3 of them. Since there are 5 in the HTML, they will remain red.

[2] Styles apply if there are at least a number of sibling elements

CSS

.siblings { background: red; }

.siblings:first-child:nth-last-child(n+3),
.siblings:first-child:nth-last-child(n+3) ~ .siblings { background: green; }

Here, the siblings will become green if there are at least 3 of them. Since there are 5 in the HTML, they will become green.


It might take a moment to wrap your head around it, but it's really not that complex. Basically you could only affect the first sibling or all the adjacent, excluding the first, by removing on of the selectors.

Using the universal selector, one might be able to come up with some powerful conditional stuff, yet carefully, since the universal selector might cause some performance issues.

Dependent on the nth-last-child selector. IE 9+ only.
If you need support, you can use selectivizr, which enables CSS3 selectors in IE6+:
http://selectivizr.com/

Warning
Selectivizr gives support for nth-last-child only with mooTools. If you're using jQuery, you need to include DOMAssistant as well.


Original discovery of this credited to André Luís:
http://andr3.net/blog/post/142

With improvement from Lea Verou:
http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/