2

If you have this html:

Fiddle: https://jsfiddle.net/qujo0w00/

<article class="type-a">Content A</article>
<article class="type-b">Content B</article>
<article class="type-b">Content B</article>
<article class="type-b">Content B</article>
<article class="type-b">Content B</article>
<article class="type-a">Content A</article>
<article class="type-b">Content B</article>
<article class="type-b">Content B</article>
<article class="type-a">Content A</article>
<article class="type-b">Content B</article>
<article class="type-b">Content B</article>

How do you target every second element that HAS type-b class? Because, if you use

.type-b:nth-of-type(2n+2) { background-color: red; }

it targets the 2nd article, even if the first article doesn't have type-b class. And then it seems to work randomly, skipping 3 articles at one point.

I'm really confused over what is going on, can anyone shed any light on this?

I even tried:

article:not(.type-a):nth-of-type(2n+2) { background-color: red; }

but still same issue.

j08691
  • 204,283
  • 31
  • 260
  • 272
capvidel
  • 359
  • 3
  • 14
  • 4
    It targets childrens, doesn't matter how classname you are defined. `nth-of-type(n)` reffers to the `n` children, not the `n with classname x` children. To make this task you need to change the html or make in javascript – Marcos Pérez Gude Mar 07 '16 at 14:08
  • 2
    In addition to Marcos' comment, you may want to have a look at BoltClock's answer [here](http://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class). It would explain how the `nth-*` selectors work. – Harry Mar 07 '16 at 14:10
  • Thanks, it makes sense now, and I will change the HTML structure. – capvidel Mar 07 '16 at 14:20

0 Answers0