gpt4 book ai didi

CSS3 意外行为 CSS 未被覆盖

转载 作者:行者123 更新时间:2023-11-28 04:38:10 25 4
gpt4 key购买 nike

我在尝试学习 CSS3 时遇到了这段代码。下面的代码结果是:我很棒,用红色写成。但是当尝试不使用 style 标签的前三行代码或将 !important 添加到 style 标签的第五行时,结果是:我很棒,用蓝色写成。谁能向我解释这种行为。

<!DOCTYPE html>
<html>
<head>
<style>
#awesome .favorite:not(#awesome) .highlight {
color: red;
}
#awesome .highlight:nth-of-type(1):nth-last-of-type(1) {
color: blue ;
}
</style>
</head>
<body>
<ul class="shopping-list" id="awesome">
<li>
<span>Milk</span>
</li>
<li class="favorite" id="must-buy">
<span class="highlight">I am awesome</span>
</li>
</ul>
</body>
</html>

最佳答案

这个选择器:

#awesome .favorite:not(#awesome) .highlight

比这个有更高的特异性:

#awesome .highlight:nth-of-type(1):nth-last-of-type(1)

在我的头脑中,我不知道nth-of-typenot 声明如何影响特异性,但粗略地说,第一个有两个类和第二个只有一个,所以它会更具体一些。

在 css 中,无论顺序如何,更具体的选择器都会覆盖不太具体的选择器,因此您的文本为红色。

当然如果你去掉红色类,那么蓝色类是最具体的,所以它会“赢”。通过添加 !important,您增加了蓝色的特异性,因此它变得比红色的更具体并且它将“获胜”。

关于CSS3 意外行为 CSS 未被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41367550/

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