1

The HTML and CSS below produce that the 1st and 4th elements get the nth-child(odd) style instead of the 1st, 3rd, 5th, ... elements.

If I continue and add additional elements with the class "one" they will be colored in the following pattern:

1st, 4th, 5th, 8th, ... and so on.

I am not sure why this is the behaviour, any alternatives that will actually work only with CSS?

.one {
  background-color:yellow;
}

.two {
  background-color:red;
}

.one:nth-child(odd) {
  color:pink;
}
<p class="one">
First Paragraph of class one
</p>
<p class="one">
Second Paragraph of class one
</p>
<p class="two">
First Paragraph of class two
</p>
<p class="one">
Third Paragraph of class one
</p>
<p class="one">
Forth Paragraph of class one
</p>
aaa
  • 601
  • 6
  • 13
  • useful: http://stackoverflow.com/a/10931957/3840840 – Sebastian Brosch Sep 07 '16 at 08:54
  • @sebastianbrosch thx for that, this is the JavaScript solution which is not optimal for me because elements will be loaded dynamically to the page, and I don't want to run calculations every time something changes. But if not solution in CSS is found, this solution will be used. so Thanks! – aaa Sep 07 '16 at 09:03

1 Answers1

-1

Try changing .one:nth-child(odd) to p:nth-child(odd) instead of using class

.one {
  background-color:yellow;
}

.two {
  background-color:red;
}

p:nth-child(odd) {
  color:pink;
}
<p class="one">
First Paragraph of class one
</p>
<p class="one">
Second Paragraph of class one
</p>
<p class="two">
First Paragraph of class two
</p>
<p class="one">
Third Paragraph of class one
</p>
<p class="one">
Forth Paragraph of class one
</p>
Hitesh Misro
  • 3,397
  • 1
  • 21
  • 50
  • 1
    But he *wants* to limit it to just the .one class. You're doing exactly what he *doesn't* want to do. – BoltClock Sep 07 '16 at 08:50
  • OP wants the pink color to be assigned in the order 1,3,5... to the elements and here it is! – Hitesh Misro Sep 07 '16 at 08:52
  • @HiteshMisro I want the pink color only on the `p.one` elements. preferably using only css because elements will be loaded dynamically to the page with inifinite scroll. some elements will have the `two` class, but I want only odd elements with the `one` class to get a certain attribute. – aaa Sep 07 '16 at 09:00