Search code examples
csshtmlpseudo-classcss-selectors

Alternating element's style using pseudo class that are in separate parents


I have several div elements and I want to alternate another set of div styles within them. So basically change the child's style to alternating background colors like so:

HTML

<article class="post"> <!--first post-->
  <div class="title">Title Here</div>
  content here
</article>

<article class="post"> <!--second post-->
  <div class="title">Title Here</div>
  content here
</article>

CSS

div.title:nth-of-type(even) {
   background-color: #F00;
}
div.title:nth-of-type(odd) {
   background-color:#00F;
}

Is there a way to do this, because I know that using css to alternate styles it has to be within a parent. Or if not would there be any jquery script that i could use?

Thank you.


Solution

  • You should use

    article.post:nth-of-type(even) .title
    

    Works fine this way.

    jsFiddle


    Also, try to stay away from over-qualified CSS selectors like div.title, as explained in this article by CSS Wizardy. Basically, the .title in this instance is definitely within the article.post, so you don't need to add the div too.

    Overqualified selectors make the browser work harder than it needs to and uses up its time; make your selectors leaner and more performant by cutting the unnecessary bits out.