The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS [Solved] :nth-child not working as expected

  • This topic is empty.
Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
  • #149787
    Clive Cooper

    Hey guys!

    What I’m trying to achieve here is this: Example

    I have six divs with two inner divs, like this:

    <div class="container">
       <div class="right"></div>

    the ‘container’ div has a bg colour of #E2E2E2 with a separate style of :nth-child(2n+2), Like this:

    .container { background: #E2E2E2;
    .container:nth-child(2n+2) { background: #C9C9C9;

    this makes the bg colour swap every second div.

    That’s all fine and dandy but where the problem lies at is with the ‘right’ div.

    The ‘right’ div has the bg colour of #C9C9C9 and again, with a separate style of :nth-child(2n+1) just like the first one (instead the colours are swapped). When I try to do this all I get is this:

    The bg colour of the ‘right’ div works, but the :nth-child does not. If someone could explain to me why it does not work that would be tremendous.



    Unfortunately, the image isn’t really informative.

    Perhaps you could show us this “not working” in Codepen?

    It might also be useful to have an image of what this is supposed to look like.

    I’m thinking, initially, that this is a specificity issue with a cascade fallback position. :)

    Clive Cooper



    Oh and btw, I did include a link to what It was supposed to look like (look near the top)


    I don’t know why either.But just add
    border: 1px solid red;
    to ‘.right’.You will see the float seems not to be what you want.


    Sorry the image was so huge I missed that it had two columns.

    As I should have guessed it was a case of the final selector not being specific enough.


    It had nothing to do with specificity – but rather was not targeting anything.

    You don’t want to target every other float child because there’s only one child for each container. You need to target the float child of every other container as Paulie has shown in his pen.

    edit// is there a reason you’re using 2n+2 and not just 2n (not that it matters here)?

    Clive Cooper

    Great, thanks guys!

    Much appreciated :)

Viewing 7 posts - 1 through 7 (of 7 total)
  • The forum ‘CSS’ is closed to new topics and replies.