假设某些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
。
答案 0 :(得分:1)
您确定您的div被称为消息而不是成员吗?
您正在寻找的是:
#members > div > span:first-of-type
#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;
希望这会有所帮助:)
答案 1 :(得分:1)
你错过了一个空间。你想要的是第一个孩子的跨度,而不是第一个孩子的div。
找到第一个范围:
#messages > div :first-child
找到第一个div:
#messages > div:first-child
答案 2 :(得分:1)
第一个类型选择器允许您这样做:
div#members span:first-of-type {
color:#000;
}