Search code examples
csscss-selectorspseudo-class

E > E:nth-child(2) pattern doesn't work. How to solve it?


I have a structure:

<div id="outer">
    <div> <!-- first div -->
        <div>  <!-- second div -->
        </div>
    </div>
</div>

I want to apply styles to the first and to the second divs using E > E:nth-child(n) pattern. But it doesn't work for the second div, only for the first one.

/* this works */
#outer > div:nth-child(1) {
    border: 1px solid red;
    padding: 10px;
}

/* this doesn't work */
#outer > div:nth-child(2) {
    border: 1px solid green;
    padding: 10px
}

Why doesn't work? How can I make it work?


Solution

  • The second div is not a direct child from #outer. So your selector #outer > div does not affect the second div as > only selects direct children. Maybe you could use

    /* this works */
    #outer > div:nth-child(1) {
        border: 1px solid red;
        padding: 10px;
    }
    
    /* this should also work */
    #outer > div:nth-child(1) > div:nth-child(1) {
        border: 1px solid green;
        padding: 10px
    }