选择<h3>类定义后的第一个元素



我有以下代码:

<div class="wrapper">
    <div class="location info">
        <h3>Location</h3>
        <h3>should be no stlye</h3>
    </div>
    <div class="skills info">
        <h3>Skills</h3>
        <h3>should be no stlye</h3>
    </div>
</div>

我试图样式的第一个h3元素后的信息类。我认为这应该可以工作,但它没有:

.info:first-child {
    color: color: rgb(200,50,50);
}

为什么不工作?我应该如何样式的第一个元素。信息没有在html中添加额外的标记?

你需要一个空格:

.info :first-child

first-child伪元素描述元素本身,而不是元素的子元素。所以,如果没有空格,你所选择的元素的info类是其父元素的第一个子元素。

空格指定您正在查找.info的后代。由于您正在寻找直接的子元素,因此您应该使用子组合符—>,并且可能还只指定h3元素:

.info > h3:first-child

编辑:我只注意到选择器的问题。正如在其他答案(+1到user1479606)中提到的,您的样式定义中也有一个错别字:color: color: ...应该是color: ...

你离得不远了,试试这个:

.info > h3:first-child {
    color: rgb(200,50,50);
}

但是,我认为最好的方法是在第一个h3中添加一个有意义的类,这将使将来阅读CSS和标记更加容易,并且在编辑标记时可以防止意外行为。例如:

.info-title {
    /* your styles here */
}

你的css不正确,你只需要指定一次color。你还需要对你的选择器做一个更小的改变:

.info > h3:first-child {
    color: rgb(200,50,50);
}

演示:http://jsfiddle.net/WSZcS/

我想样式的第一个h3元素后的信息类。

.info > h3 {
    color: rgb(200,50,50);
}

如果h3不是第一个子元素,可以使用

.info > h3:first-of-type {
    color: rgb(200,50,50);
}

相关内容

最新更新