Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make nth-child work with descendant selectors?

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.

like image 649
lala Avatar asked Aug 29 '13 18:08

lala


2 Answers

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 .myDivs I don't think any CSS will work for what you want to do.

like image 190
Explosion Pills Avatar answered Sep 27 '22 19:09

Explosion Pills


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 divs only:

div.myDiv:nth-of-type(odd) div {
    color: red;
}

div.myDiv:nth-of-type(even) div {
    color: blue;
}

Or if there are other divs 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.

like image 31
BoltClock Avatar answered Sep 27 '22 19:09

BoltClock