1

I have some code that isn't working and I'm not sure why.

The html looks like this:

<section>
</section>

<section>
</section>

<section>
</section>

<section>
</section>

The CSS looks like:

 section {
      min-height: 200px;
}

 section:nth-child(odd) {
      background: #F5E9DE;
}

 section:nth-child(even) {
      background: #fefcfb;
}

 section:nth-last-child(2) {
      background: #B97459;
}

 section:last-child {
    background: #38292c;
}

Fiddle: https://jsfiddle.net/bxuzs3g0/8/

The idea is simple, alternate the odd and even backgrounds, then the last two sections should have specific background colors. This way I can have as many sections as I want, but the last two sections always have specific background colors.

I'm not sure what I'm doing wrong here, I have tried nth-last-child(1) and last-child, but for some reason neither combination is working for me.

I know this one's probably pretty easy, can anyone point me in the right direction?

Thanks,
Josh

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
Josh Rodgers
  • 507
  • 7
  • 27
  • 2
    always consider your own container to be sure it's accurate and works everywhere – Temani Afif Jul 09 '18 at 15:05
  • 3
    You need to wrap your sections in a parent div to ensure they truly are the only children. In this example, JSFiddle adds a – Joel Worsham Jul 09 '18 at 15:05
  • 1
    I see this is a duplicate, but I wanted to say thanks! I just had to add an outer container and everything started working! – Josh Rodgers Jul 09 '18 at 15:18
  • alternatively, you can replace `*-child` with `*-of-type`, to count only elements with the same type (tag name), in this case, `section` – Ilya Streltsyn Jul 09 '18 at 15:31
  • Hmm...that's also a good idea, hadn't thought about that one :-) Thanks for the suggestion! – Josh Rodgers Jul 09 '18 at 15:33
  • 1
    @IlyaStreltsyn no it's not a good idea, because you don't know the tag that are added automatically ... Maybe in this case jsfiddle won't add section tag but what if we will later change section to div or something else? what if another online tool add hidden section tag? it's still random and not accurate, so in all the cases it's good to have a container and don't rely on random things that we cannot control – Temani Afif Jul 09 '18 at 16:08

0 Answers0