假设我的html看起来像这样:
<div class="container">
<... some html here ...>
</div>
我希望得到.container
的第一个直接孩子。
我可以做.container > div:first-child
但是假设它是div
并非总是如此。
答案 0 :(得分:6)
使用不带标记名的:first-child
伪类:
.container > :first-child
这将抓取任何直接第一个子元素,无论其标记名如何。这类似于我们使用其他伪类的方式,例如:hover
仅针对任何元素,而a:hover
仅针对锚点的悬停状态。
答案 1 :(得分:0)
不使用元素本身,但是一个类是一个更好的解决方案,并且因为很多原因语义。
将类提供给元素的子元素,而不仅仅是像这样的容器:
HTML:
<article class="container">
<p class="blah">First paragraph...</p>
<p class="blah">Lorem ipsum...</p>
<p class="blah">Dolor sit amet...</p>
</article>
CSS:
.blah {
background: red;
color: white;
}
.blah:first-child {
background: #000;
}
您可以在此处看到它:http://jsfiddle.net/Roobyx/ygP4B/