gpt4 book ai didi

CSS 继承与 CSS 特异性

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

我在大学计算机科学系的 Web 开发课上,老师问类(class):“为什么类选择器规则应用在标签选择器规则之上(参见示例代码)?”。我回答说这是因为 CSS 的特殊性,我被告知我错了。他想要的答案是因为 CSS 继承。

虽然这是真的,但为什么 CSS 特异性是一个错误的答案?

p {
color: red;
}

.section {
color: green;
}
<p class="section">Section</p> 

最佳答案

正如我在评论中所说,我相信你是对的:CSS 中的继承与 DOM 层次结构相关。 Certain styles继承自父元素。

Specificity与哪些 CSS 规则优先于其他 CSS 规则有关。请参阅下面的一些示例。

.container {
font-size: 35px;
}

p {
color: red;
}

.section {
color: green;
}

div.section {
/* More specific then .section rule */
color: purple;
}
<div class="container">
<p>
Example of inheritance. This paragraph has inherited the font-size of its parent.
<span>This span also inherited font-size.</span>
</p>
</div>

<div>
<p class="section">
Example of specificity. The "section" class is more specific than the rule created for the p element. Therefore, styles defioned in the "section" class rule may override those defined in the p element rule.
</p>

<p>
No class applied.
</p>

<div class="section">
The "div.section" rule is more specific than the ".section" rule, so this text is purple.
</div>
</div>

关于CSS 继承与 CSS 特异性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58205835/

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