How to use nth-of-type to select nested children

I am trying to create odd and even headings related to content. They are inside several DIVs, and I cannot get nth-child or nth-of-type to work, only odd styles are displayed. Here are some conceptual codes:

HTML:

<div class="content"> <h2>Welcome to my blog</h2> <div class="post"> <h2><a href="myPostLink">This is a post</a></h2> <div class="entry"> <p>here is some content</p> </div> <!-- end entry --> <div class="meta"><p>Here is meta info</p></div> </div> <!-- end post --> <div class="post"> <h2><a href="myPostLink">This is another post</a></h2> <div class="entry"> <p>here is some more content</p> </div> <!-- end entry --> <div class="meta"><p>Here is meta info</p></div> </div> <!-- end post --> </div> <!-- end content --> 

CSS

 .content h2 a:nth-of-type(odd){color: #444;} .content h2 a:nth-of-type(even){color: #ccc;} 

jsfiddle

My thinking process was that, starting with .content in my CSS, the first .content h2 a will be considered odd, and the second even, etc. Apparently not so - they are all considered the first child. Is there a way to select the headers the way I want, only using CSS? Am I doing something stupid?

Thanks,

Ricky

+8
css css-selectors
source share
2 answers

Use nth-child for .post elements, and then select the h2 element

JsFiddle example

 .post:nth-child(odd) h2 a { color: red; } .post:nth-child(even) h2 a { color: green; } 
+12
source share

try it

 .content div.post:nth-of-type(odd) a{color: #444;} .content div.post:nth-of-type(even) a{color: #ccc;} 

An odd and even divs element with a post class. Not quite sure what you need. Working example: http://jsfiddle.net/a4j7z/

+3
source share

All Articles