简体   繁体   English

将CSS选择器与:first-child组合

[英]Combining CSS Selectors with :first-child

Suppose some HTML contains the following div block: 假设一些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>

How could I style the "from user" text (and just that text) using CSS selectors? 如何使用CSS选择器设置“来自用户”文本(以及仅该文本)的样式? I tried to select the first-child element of the child div of div #messages using #messages>div:first-child , but that didn't work. 我尝试使用#messages>div:first-child选择div #messages的子divfirst-child元素,但这没有用。

EDIT: 编辑:

There was a small mistake in my syntax. 我的语法有一个小错误。

The proper CSS selector rule should be #messages>div>:first-child rather than what I tried earlier ( #messages>div:first-child ). 正确的CSS选择器规则应该是#messages>div>:first-child而不是我之前尝试过的规则( #messages>div:first-child )。 The difference is in the > I missed after div . 区别在于> div之后我错过了。

Are you sure your div is called messages and not members ? 您确定您的div被称为消息而不是成员吗?

What you're looking for is: 您正在寻找的是:

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

 #members > div > span:first-of-type { color: #f00; } 
 <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> 

Hope this helps :) 希望这可以帮助 :)

You're missing a space. 您缺少空格。 You want the span that's the first child, not the div that's the first child. 您想要的跨度是第一个孩子,而不是div是第一个孩子。

Finds the first span: 查找第一个跨度:

#messages > div :first-child

Finds the first div: 查找第一个div:

#messages > div:first-child

The first-of-type selector would allow you to do that: 第一类选择器将允许您执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM