【问题标题】::first-child not working as expected:first-child 没有按预期工作
【发布时间】:2011-05-29 04:30:06
【问题描述】:

我正在尝试使用名为 detail_container 的类选择 div 中的第一个 h1。如果h1 是这个div 中的第一个元素,它可以工作,但如果它出现在这个ul 之后,它将不起作用。

<style type="text/css">
.detail_container h1:first-child
{
color:blue;
} 
</style>
</head>
<body>
<div class="detail_container">
    <ul>
    <li></li>
    <li></li>
    </ul>
    <h1>First H1</h1>
    <h1>Second H1</h1>
</div>
</body>
</html>

我的印象是,我拥有的 CSS 将选择第一个 h1,无论它在此 div 中的哪个位置。我怎样才能让它发挥作用?

【问题讨论】:

  • CSS 做不到的,JavaScript 可以。
  • 这是你可以用 CSS3 做的事情 :)

标签: css css-selectors


【解决方案1】:

h1:first-child 选择器表示

选择其父级的第一个子级
当且仅当它是一个 h1 元素。

这里容器的:first-childul,因此不能满足h1:first-child

您的情况有 CSS3 的 :first-of-type

.detail_container h1:first-of-type
{
    color: blue;
} 

但是由于浏览器兼容性问题等等,你最好给第一个 h1 一个类,然后定位那个类:

.detail_container h1.first
{
    color: blue;
}

【讨论】:

  • 我现在明白了,尽管我认为他们在创建标准时应该实现了这两个版本。
  • 在 IE9 版本中不工作。它说 h1:unknown in developer tool
  • Compatibility list of :first-of-type 选择器。
  • Newer compatibility list of :first-of-type。旧链接不正确。
  • 在我看来,:first-child 这个词不太好理解,因为您将项目定义为 CSS 选择器,比如 h1,然后您随后会想到“取第一个孩子”在所选的 DOM 级别中。我用错了很多次......我们必须习惯:first-of-type选择器并考虑其类型的第一个孩子
【解决方案2】:

:first-child 选择第一个 h1 当且仅当它是其父元素的第一个子元素。在您的示例中,uldiv 的第一个孩子。

伪类的名称有些误导,但在规范中here 解释得很清楚。

jQuery 的:first 选择器为您提供所需的内容。你可以这样做:

$('.detail_container h1:first').css("color", "blue");

【讨论】:

  • 你说得对,这是误导,我主要是因为我之前使用过 jQuery 来做到这一点而感到困惑。
【解决方案3】:

对于这种特殊情况,您可以使用:

.detail_container > ul + h1{ 
    color: blue; 
}

但是如果你在很多情况下都需要相同的选择器,你应该为这些选择一个类,就像 BoltClock 说的那样。

【讨论】:

【解决方案4】:

你也可以使用

.detail_container h1:nth-of-type(1)

通过将数字 1 更改为任何其他数字,您可以选择任何其他 h1 项目。

【讨论】:

    【解决方案5】:

    您可以将h1 标签包装在另一个div 中,然后第一个标签就是first-childdiv 甚至不需要样式。这只是隔离这些孩子的一种方式。

    <div class="h1-holder">
        <h1>Title 1</h1>
        <h1>Title 2</h1>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2013-01-12
      • 2013-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2021-10-19
      相关资源
      最近更新 更多