I have this code.
<div class="myDiv">
<div>
I want to be red.
</div>
</div>
<p>I'm some other content on the page</p>
<div class="myDiv">
<div>
I want to be blue.
</div>
</div>
.myDiv div:nth-child(odd) {
color: red;
}
.myDiv div:nth-child(even) {
color: blue;
}
I see why it's not working. It's making every odd div within myDiv be red. What I want it to do is make every odd example of a div within myDiv be red. How can I write that?
Here's a JSFiddle.
There are a couple of problems here. The :nth-child
is on the wrong element. The inner divs are always the first child, so the :nth-child(odd)
selector works for both. Instead move to
.myDiv:nth-child(odd) div
...however this does not work either because of the <p>
. A working solution with your sample is
.myDiv:nth-of-type(odd) div
http://jsfiddle.net/tvKRL/1/
NOTE that the nth-of-type
only works because the .myDiv
elements are all divs (it's based on the element, not the selector), so the selector ignores the <p>
. If there can be another div between .myDiv
s I don't think any CSS will work for what you want to do.
You can't do this generically, for the reason given by Domenic. To put it simply: there's no selector that lets you filter an existing subset of matched elements.
On the off chance that among your p
and div.myDiv
siblings the only div
elements are the ones with that class anyway, then you could use :nth-of-type()
to have it look at those intermediate div
s only:
div.myDiv:nth-of-type(odd) div {
color: red;
}
div.myDiv:nth-of-type(even) div {
color: blue;
}
Or if there are other div
s without that class which should be excluded, then unless there is some sort of pattern in which they're laid out, you're out of luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With