【问题标题】:Possible to select the first child (when the first element will often be different)可以选择第一个子元素(当第一个元素通常不同时)
【发布时间】:2018-01-11 04:53:49
【问题描述】:

我的div 有时以ph2h3ul 开头。有没有办法选择div的第一个元素,不管元素是什么?

这是一个 JSFiddle https://jsfiddle.net/nv0mg602/

在第一个 div 中,我希望第一个 p 是红色的,而不是两个 p。在第二个 div 中,我希望第一个 h2 是红色的。

谢谢大家。我意识到.main:first-child 不起作用,但.main :first-child 起作用(在主和冒号之间有一个空格)

【问题讨论】:

  • 只需做:first-child
  • 我也写 main:first-child { background:red; } ?
  • 为什么你不简单地试试看 :) 你会得到答案
  • 它什么也没做!

标签: css


【解决方案1】:

您应该将 :first-child 选择器与 child 项而不是父项一起使用,并且由于您想考虑所有子项(无论标签/类是什么),您必须使用 通用选择器*(但它不是强制性的,如下所示)。

这是一个例子:

.main *:first-child {
    color: red;
}
/* or simply
.main :first-child {
    color: red;
}
*/

/* or use this to select ONLY direct childs
.main > :first-child {
    color: red;
}
*/
<div class="main">
  <p>
  Hello some type
  </p>
  <p>
  And some more
  </p>
</div>

<div class="main">
  <h2>
  A heading
  </h2>
  <p>
  And some more text
  </p>
</div>

【讨论】:

  • 太棒了!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2015-06-07
  • 2018-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多