gpt4 book ai didi

html - CSS 在孙子中选择第一个类型?

转载 作者:太空狗 更新时间:2023-10-29 14:43:08 30 4
gpt4 key购买 nike

我读过棘手的问题,例如 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 元素,它进一步嵌套为 direct child到具有 .parent

class 的元素

> 表示选择其父级的直接后代。


以上将在旧版本的 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

关于html - CSS 在孙子中选择第一个类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22461894/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com