0

I want to make some boxes have different properties based on whether they're the odd or even number box in the group but only for a selector of multiple classes: But it's including the original box class's object despite it not being in the CSS selector for nth-child:

http://jsfiddle.net/wLx67r83/

<div class="box">1</div>
<div class="box special">1</div>
<div class="box special">1</div>

.box
{
    width: 100px;
    height: 50px;
    background-color: #e3e3e3;
}

.box.special:nth-child(odd)
{
    background-color: red;
}

.box.special:nth-child(even)
{
    background-color: blue;
}

The third box should be blue, but it's red! And the second should be red, but it's blue!

Don Rhummy
  • 24,730
  • 42
  • 175
  • 330

2 Answers2

1

You have to change the even/odd around in the css.

http://jsfiddle.net/wLx67r83/6/

<div class="box">1</div>
<div class="box special">1</div>
<div class="box special">1</div>

.box
{
    width: 100px;
    height: 50px;
    background-color: #e3e3e3;
}

.special:nth-child(even)
{
    background-color: red;
}

.box.special:nth-child(odd)
{
    background-color: blue;
}

Edit: Or you can choose the formula option http://jsfiddle.net/wLx67r83/28/

.special:nth-child(2n+0)
{
    background-color: red !important;
}
.special:nth-child(2n+3)
{
    background-color: blue !important;
}
DaedalusZ
  • 56
  • 3
  • this doesn't fix the problem. There could be an additional `
    1
    ` added to the beginning which would make your solution wrong again. The problem is how to start counting from the first ".special"?
    – Don Rhummy Nov 07 '14 at 19:49
  • His solution actually does work, unless it's important for the first `.special` class to be red: http://jsfiddle.net/wLx67r83/14/ – Axel Nov 07 '14 at 19:57
  • @Axel it does not work. You just happened to make that second group start on an even number. You can see the problem here: http://jsfiddle.net/wLx67r83/22/ – Don Rhummy Nov 07 '14 at 20:14
  • Can you use a formula like (an + b), does it have to be even and odd? e.g http://jsfiddle.net/wLx67r83/28/ – DaedalusZ Nov 07 '14 at 20:46
-1

nth-child is counting from the parent's child nodes. The correct answer is nth-of-type:

.box.special:nth-of-type(odd)
{
    background-color: red;
}

.box.special:nth-of-type(even)
{
    background-color: blue;
}
Don Rhummy
  • 24,730
  • 42
  • 175
  • 330
  • But this produces the exact same results as your original fiddle? http://jsfiddle.net/wLx67r83/2/ – Axel Nov 07 '14 at 19:41
  • @Axel oddly, you're right. It works in my own web page but not on jsfiddle! Why? – Don Rhummy Nov 07 '14 at 19:42
  • 2
    No idea, but `nth-child` and `nth-of-type` both behave similar in that it counts from the parent. What you're wanting is a `nth-of-class`, [but that doesn't exist in CSS](http://stackoverflow.com/a/5428766/1332068). Better to wrap the special divs in their own parent div to guarantee the correct results. – Axel Nov 07 '14 at 19:45