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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/html/225415.html

猜你在找的HTML相关文章