CSS在孙子中选择第一类型? [英] CSS select first-of-type amongst grandchildren?
问题描述
我已阅读过棘手的问题,例如使用CSS选择第一个后代或< a href =http://stackoverflow.com/questions/18772494/how-do-i-hide-only-the-first-element-of-a-type>如何仅隐藏类型的第一个元素
我有这个HTML结构:
< div class =parent>
< div>
< p class =interline><! - only this - >
< p class =interline>
< p class =interline>
< / div>
< div>
< p class =interline>
< p class =interline>
< p class =interline>
< / div>
< / div>
并且只想选择第一个孙子< p> $
您还需要选择第一个 div
以及
.parent> div:first-of-type> p:first-of-type {
color:red;
}
在上述选择器中,第一个 p
元素嵌套在第一个 div
内,它进一步嵌套为具有 class
of .parent
上述将会在较旧版本的Internet Explorer中失败,因此如果您正在寻求支持它们,那么等效的支持的选择器将是
.parent> div:first-child> p:first-child {
color:red;
}
演示 (也支持IE7)
但是使用 :first- child
和 :first-of-type
有很大的区别,比如你使用 p:first-child
并且除了 p
之外还有一些其他元素,您的选择器将失败,所以这就是为什么我提供了使用:first-of-type
I've read tricky questions such as Select first Descendant with CSS or How do I hide only the first element of a type? but mine doesn't match these ones.
I have this HTML structure:
<div class="parent">
<div>
<p class="interline"><!-- only this -->
<p class="interline">
<p class="interline">
</div>
<div>
<p class="interline">
<p class="interline">
<p class="interline">
</div>
</div>
And want to select only the first grandchild <p>
under the .parent div.
How do I do that?
You need to select the first div
as well
.parent > div:first-of-type > p:first-of-type {
color: red;
}
Here in the above selector, I am selecting the first p
element nested inside the first div
, which is further nested as direct child to an element having a class
of .parent
>
means select direct descendant to it's parent.
The above will fail in older versions of Internet Explorer, so if you are looking to support them as well, than equivalent supported selector will be
.parent > div:first-child > p:first-child {
color: red;
}
Demo (Supports IE7 as well)
But using :first-child
and :first-of-type
has huge difference, say you are using p:first-child
and you have some other element apart from p
, your selector will fail, so that's why I provided you a solution of using :first-of-type
这篇关于CSS在孙子中选择第一类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!