如何使用nth-of-type选择嵌套子代

ric*_*cky 10 css css-selectors

我正在尝试设置与内容相关联的奇数和偶数标题.它们在几个DIV中,我无法让nth-child或nth-of-type工作 - 只有奇怪的样式显示.这是一些概念代码:

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 -->
Run Code Online (Sandbox Code Playgroud)

CSS:

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

的jsfiddle

我的思维过程是因为我在CSS中开始.content,第一个.content h2 a被认为是奇数,第二个是偶数,等等.显然不是这样 - 他们都被认为是第一个孩子.有没有办法以我想要的方式单独选择标题?我在做一些蠢事吗?

Jos*_*ier 17

nth-child.post元素上使用,然后h2从那里选择元素

jsFiddle例子

.post:nth-child(odd) h2 a {
    color: red;
}
.post:nth-child(even) h2 a {
    color: green;
}
Run Code Online (Sandbox Code Playgroud)


MaG*_*tas 6

尝试这个

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

带有 post 类的奇数和偶数 div 元素。不太确定这是否是您所需要的。一个工作示例:http : //jsfiddle.net/a4j7z/