Jamie Hutber
Jamie Hutber

Reputation: 28074

Css selector target if x elements

Simply I'd like to target one rule if there are 3 divs and another if there are 4 divs.

Markup

//one set of rules
<div></div>
<div></div>
<div></div>

//second fules
<div></div>
<div></div>
<div></div>
<div></div>

CSS

/* three items */
div:nth-child(1):nth-last-child(3),
div:nth-child(2):nth-last-child(2),
div:nth-child(3):nth-last-child(1)

/* fouritems */
div:nth-child(1):nth-last-child(4),
div:nth-child(2):nth-last-child(3),
div:nth-child(3):nth-last-child(2),
div:nth-child(4):nth-last-child(1)

I've followed this: http://lea.verou.me/2011/01/styling-children-based-on-their-number-with-css3/ but not with much luck sadly.

Upvotes: 1

Views: 580

Answers (1)

BoltClock
BoltClock

Reputation: 723528

In your fiddle, the following selector:

.stepNav li span:nth-child(1):nth-last-child(4), 
.stepNav li span:nth-child(2):nth-last-child(3), 
.stepNav li span:nth-child(3):nth-last-child(2), 
.stepNav li span:nth-child(4):nth-last-child(1)

Matches all span elements when there are exactly 4 of them in the same parent. But you only have one span per li, making each span the only child, not one of four.

What you're looking to do is to style the span elements when there are exactly 4 li elements, so you need to move the pseudo-classes over:

.stepNav li:nth-child(1):nth-last-child(4) span, 
.stepNav li:nth-child(2):nth-last-child(3) span, 
.stepNav li:nth-child(3):nth-last-child(2) span, 
.stepNav li:nth-child(4):nth-last-child(1) span

Updated fiddle, where you can see all the spans are now shaded black.

Upvotes: 1

Related Questions