【问题标题】:First child selector doesn't work if header is present如果标题存在,第一个子选择器不起作用
【发布时间】:2014-03-11 12:19:27
【问题描述】:

我有一个带有标题和一些部分的简单 HTML。

<header>Header</header>
<section>Section 1</section>
<section>Section 2</section>
<section>Section 3</section>

我想为第一部分设置样式

section:first-child {
    background-color:green;    
}

当存在header (jsfiddle) 时,:first:child 选择器似乎不起作用。当我删除 header 时,一切都恢复正常了!为什么?

【问题讨论】:

  • 对于旧浏览器,.parent &gt; section:first-child, .parent &gt; header:first-child + section
  • @Mr_Green 有用的补充,谢谢!

标签: css css-selectors


【解决方案1】:

这是因为&lt;section&gt; 不是其父级的第一个子级。

element:first-child 表示其父元素的第一个子元素,与元素匹配。在您的情况下,父元素的第一个元素是 &lt;header&gt; 元素。

您可以改用:first-of-type 伪类。

section:first-of-type {
    background-color:green;    
}

来自MDN:

:first-of-type CSS 伪类表示第一个同级 它在其父元素的子元素列表中的类型。

【讨论】:

  • 感谢您的解释!
【解决方案2】:

您应该申请first-of-type。

section:first-of-type {
    background-color:green;    
}

【讨论】:

  • 你只赢了我 2 秒。太棒了。
  • @HashemQolami 你的回答很有解释性,但做得很好!
【解决方案3】:

应该试试:first-of-type伪类

section:first-of-type {
    background-color:green;    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-02
    • 1970-01-01
    • 2014-02-15
    • 2023-03-16
    • 2014-02-21
    相关资源
    最近更新 更多