可以选择第一个孩子(当第一个元素经常不同时)

时间:2018-01-10 20:14:01

标签: css

我的div有时以p h2 h3ul开头。有没有办法选择div的第一个元素,无论元素是什么?

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

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

谢谢大家。我已经意识到.main:first-child不起作用,但是.main :first-child确实(主要和冒号之间有空格)

1 个答案:

答案 0 :(得分:1)

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

以下是一个例子:

&#13;
&#13;
.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;
}
*/
&#13;
<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>
&#13;
&#13;
&#13;