我的div
有时以p
h2
h3
或ul
开头。有没有办法选择div
的第一个元素,无论元素是什么?
这是一个JSFiddle https://jsfiddle.net/nv0mg602/
在第一个div中,我希望第一个p
为红色,而不是p
。在第二个div中,我希望第一个h2
为红色。
谢谢大家。我已经意识到.main:first-child
不起作用,但是.main :first-child
确实(主要和冒号之间有空格)
答案 0 :(得分:1)
您应该将:first-child
选择器与子项一起使用而不是父项,并且由于您要考虑所有子项(标签/类都是),您必须使用< strong>通用选择器*(但它不是强制性的,如下所示)。
以下是一个例子:
.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;