【问题标题】:Combining CSS Selectors with :first-child将 CSS 选择器与 :first-child 结合使用
【发布时间】:2017-08-04 06:35:15
【问题描述】:

假设某些 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 选择器设置“来自用户”文本(以及该文本)的样式?我尝试使用#messages&gt;div:first-child 选择div #messages 的子divfirst-child元素,但这不起作用。

编辑:

我的语法有一个小错误。

正确的 CSS 选择器规则应该是 #messages&gt;div&gt;:first-child 而不是我之前尝试过的 (#messages&gt;div:first-child)。区别在于&gt; 我在div 之后错过了。

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    您缺少一个空格。你想要的是第一个孩子的跨度,而不是第一个孩子的 div。

    找到第一个跨度:

    #messages > div :first-child
    

    找到第一个 div:

    #messages > div:first-child
    

    【讨论】:

      【解决方案2】:

      您确定您的 div 名为 messages 而不是 members

      您正在寻找的是:

      #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>

      希望这会有所帮助:)

      【讨论】:

        【解决方案3】:

        first-of-type 选择器将允许您这样做:

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

        【讨论】:

          猜你喜欢
          • 2013-01-23
          • 1970-01-01
          • 2014-05-21
          • 2014-12-18
          • 1970-01-01
          • 2018-07-09
          • 1970-01-01
          • 1970-01-01
          • 2021-07-31
          相关资源
          最近更新 更多