max*_*yme 6 html css css-selectors css3
我读过一些棘手的问题,比如用CSS选择第一个后代或者如何只隐藏一个类型的第一个元素?但我的不符合这些.
我有这个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>
Run Code Online (Sandbox Code Playgroud)
并且只想选择<p>.parent div下的第一个孙子.
我怎么做?
Mr.*_*ien 13
您需要选择第一个div,以及
.parent > div:first-of-type > p:first-of-type {
color: red;
}
Run Code Online (Sandbox Code Playgroud)
在上面的选择器中,我选择p嵌套在第一个元素中的第一个元素div,它进一步嵌套为具有a 的元素的直接子元素class.parent
> 意味着选择直接后代到它的父亲.
在旧版本的Internet Explorer中,上述操作会失败,因此如果您也希望支持它们,那么等效的支持选择器也是如此
.parent > div:first-child > p:first-child {
color: red;
}
Run Code Online (Sandbox Code Playgroud)
Demo (也支持IE7)
但是使用:first-child并且:first-of-type有很大差异,比如说你正在使用p:first-child并且你还有其他一些元素p,你的选择器会失败,所以这就是为什么我为你提供了一个使用的解决方案:first-of-type