gpt4 book ai didi

html - 非最后一个 child 应用 :last-child 定义的 CSS 样式

转载 作者:行者123 更新时间:2023-11-28 03:24:46 25 4
gpt4 key购买 nike

我刚刚发现 CSS 类是否由子选择器定义,例如':last-child', 非last children 会意外地被应用到这个类中。 span.item 在我看来也是 div.list 的 child ,只是不是直接的。我的代码如下。那么 :last-child, :first-child 和 nth-child 是否只适用于直接 child ?如果为真,是否有办法使其按预期工作?

<style>
.list .item {
color: green;
}
.list .item:last-child {
color: red;
}
</style>

<div class="list">
<p class="item">Clothes</p> <!-- GREEN -->
<p class="item">Shoes</p> <!-- RED -->
<p><span class="item">Clothes</span></p> <!-- RED, which is expected to show green text -->
<p><span class="item">Shoes</span></p> <!-- RED -->
</div>

添加了更多。谢谢大家回复。我这里举的例子是一个非常简单的例子,事实上我在工作中遇到了一个更复杂的案例。在这种情况下,类“item”必须应用于后代元素而不是直接子元素。我可以在这里使当前样本更复杂。

<style>
.list .item {
color: green;
padding: 10px;
}
.list .item:last-child {
color: red;
}

.item-detail {
color: yellow;
padding: 15px;
}
</style>

<div class="list">
<p class="item">Clothes</p> <!-- GREEN -->
<p class="item">Shoes</p> <!-- RED -->
<p class="item-detail">
Show detailed info of following item. <!-- YELLOW-->
<span class="item">Clothes</span> <!-- RED, which is expected to show green text -->
</p>
<p><span class="item">Shoes</span></p> <!-- RED -->
</div>

最佳答案

:last-child:last-of-type 的问题在于它们不尊重类...

正如我在这里看到的模式,您正在尝试交替应用颜色,因此您可以使用 nth-of-type(even) pseudo

.list p:nth-of-type(even) {
color: red;
}

.list p {
color: green;
}

Demo


现在我将解释你的选择器是如何工作的,你有这个 .list .item 意味着它将颜色应用到 pspan它们嵌套在具有 .listclass 的元素中。

很好,关于 .list .item:last-child 的第二个选择器将选择嵌套在 p 元素中的最后一个子元素。正如我所说,它不会尊重类...因此,由于 spanp 中的 last-child,它们将被选中.


如果您愿意更改标记,则将 p 元素包装在 div

HTML

<div class="list">
<div>
<p class="item">Clothes</p> <!-- GREEN -->
<p class="item">Clothes</p> <!-- GREEN -->
<p class="item">Shoes</p> <!-- RED -->
</div>
<div>
<p class="item">Clothes</p> <!-- GREEN -->
<p class="item">Shoes</p> <!-- RED -->
</div>
</div>

CSS

.list > div p:last-child {
color: red;
}

.list p {
color: green;
}

Demo

关于html - 非最后一个 child 应用 :last-child 定义的 CSS 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21980129/

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