将CSS选择器与:first-child结合使用

时间:2017-03-14 03:29:00

标签: html css css-selectors

假设某些HTML包含以下div块:

<div id="messages">
    <div>
        <span>from user</span>
        <span>The content of the message</span>
        <time datetime="2017-02-15T19:21:20.848Z">10 hours ago</time>
    </div>
</div>

我如何使用CSS选择器设置“来自用户”文本(以及该文本)的样式?我尝试使用first-child选择div div的子#messages元素#messages>div:first-child,但这不起作用。

修改

我的语法有一个小错误。

正确的CSS选择器规则应该是#messages>div>:first-child而不是我之前尝试过的(#messages>div:first-child)。不同之处在于>之后我错过的div

3 个答案:

答案 0 :(得分:1)

您确定您的div被称为消息而不是成员吗?

您正在寻找的是:

#members > div > span:first-of-type

&#13;
&#13;
#members > div > span:first-of-type {
  color: #f00;
}
&#13;
<div id="members">
    <div>
        <span>from user</span>
        <span>The content of the message</span>
        <time datetime="2017-02-15T19:21:20.848Z">10 hours ago</time>
    </div>
</div>
&#13;
&#13;
&#13;

希望这会有所帮助:)

答案 1 :(得分:1)

你错过了一个空间。你想要的是第一个孩子的跨度,而不是第一个孩子的div。

找到第一个范围:

#messages > div :first-child

找到第一个div:

#messages > div:first-child

答案 2 :(得分:1)

第一个类型选择器允许您这样做:

div#members span:first-of-type {
   color:#000;
}