如何使用nth-of-type选择嵌套子代 [英] How to use nth-of-type to select nested children

查看:202
本文介绍了如何使用nth-of-type选择嵌套子代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置与内容关联的奇数和偶数标头的样式.它们位于多个DIV中,我无法使nth-child或nth-of-type起作用-仅显示奇怪的样式.这是一些概念代码:

I am trying to style odd and even headers that are associated with content. They are inside several DIVs, and I am unable to get nth-child or nth-of-type to work- only the odd styles are displaying. Here is some concept code:

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 被认为是奇数,第二个被认为是偶数,依此类推.显然不是,他们都被认为是第一个孩子.有没有一种方法可以单独使用CSS来选择标题?我在做蠢事吗?

My thought process was that since I was starting at .content in my CSS, the first .content h2 a would 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 in the way I want with CSS alone? Am I doing something dumb?

推荐答案

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

Use nth-child on the .post elements, and then select the h2 element from there

jsFiddle示例

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

这篇关于如何使用nth-of-type选择嵌套子代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆