微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html – CSS选择孙子中的第一类?

我读过诸如 Select first Descendant with CSSHow 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>在.parent div下.

我怎么做?

解决方法

您还需要选择第一个div
.parent > div:first-of-type > p:first-of-type {
    color: red;
}

Demo

在上面的选择器中,我选择嵌套在第一个div中的第一个p元素,它进一步嵌套为具有.parent类的元素的直接子元素.

>意味着选择直接后代到它的父亲.

在旧版本的Internet Explorer中,上述操作会失败,因此如果您也希望支持它们,那么等效的支持选择器也是如此

.parent > div:first-child > p:first-child {
    color: red;
}

Demo(也支持IE7)

但是使用:first-child:first-of-type有很大的不同,比如说你使用的是p:first-child而且除了p之外还有其他一些元素,你的选择器会失败,所以这就是为什么我为你提供了一个使用的解决方案:first-of-type

原文地址:https://www.jb51.cc/html/225415.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐