Reputation: 147
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.
Upvotes: 0
Views: 1128
Reputation:
You should use
article.post:nth-of-type(even) .title
Works fine this way.
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.
Upvotes: 2
Reputation: 33870
nth-of-type
is alway checking for the postition of the element in his parent. Hence, your div's
are always first child of .post
. That's why it doesnt work.
But you can check the child position of it's parent. Just like that :
.post:nth-of-type(even) div.title{}
.post:nth-of-type(odd) div.title{}
Upvotes: 1