0

I have a list of elements to wich I want to add a different color depending on the even/odd BUT only elements with a special class.

<!DOCTYPE html>
<html>
  <head>
    <style> 
      p.class:nth-of-type(odd) {
       background: #ff0000 ;
      }

      p.class:nth-of-type(even) {
       background: #0000ff ;
      }
    </style>
  </head>
  <body>
    <p class="class">The first paragraph.</p>
    <p>The second paragraph.</p>
    <p class="class">The third paragraph.</p>
    <p class="class">The fourth paragraph.</p>
  </body>
</html>

The result I expect is :

  • red
  • normal
  • blue
  • red

But the real result is :

  • red
  • normal
  • red
  • blue

Thanks for your answers.

3 Answers3

2

This is because the odd/even is based off of what position it is relative to its parent, not relative to its "like" divs. It would be most efficient just to give the divs individual classes.

AETech
  • 65
  • 6
2

It doesn't appear that you can target classes, so regardless of what the class is it uses the p tag as the type (see the below link):

css3 nth of type restricted to class

Community
  • 1
  • 1
Drew
  • 3,194
  • 8
  • 40
  • 62
1

If you allowed to use jQuery I would suggest the following snippet to set odd/even classes. You can't do it with pure CSS anyway as it was discussed here: css3 nth of type restricted to class

Here is the snippet: http://jsfiddle.net/webyourway/wsfxxcn9/11/

$(document).ready(function () {
    $('.class').each(function(i){
        if (i % 2 == 0) {
            $(this).addClass('even');
        } else  {
            $(this).addClass('odd');
        }
    });
})

You can use any version of jQuery.

Community
  • 1
  • 1
Valera Tumash
  • 628
  • 7
  • 16