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

时间:2013-12-15 20:31:57

标签: 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 -->

CSS:

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

JSFiddle

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

2 个答案:

答案 0 :(得分:15)

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

jsFiddle example

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

答案 1 :(得分:3)

试试这个

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

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

相关问题