我在大学计算机科学系的Web开发班上,老师问班级为什么要通过简单的段落标签调用班级(请参见示例代码)。我回答说是因为CSS特殊性,所以我被告知我错了。他想要的答案是因为CSS继承。
虽然是正确的,但为什么CSS特异性是错误的答案?
p {
color: red;
}
.section {
color: green;
}
<p class="section">Section</p>
.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>
这是一个快速的结构示例,可能有助于解释一些;
p
元素。p { color: red; }
p
声明的所有内容,并且将覆盖您指定的属性,但只限于使用此特定类的p
元素。.section { color: green; }
p[class=section] { color: blue; }
以及一些上下文示例,希望能有所帮助;
p { color: red; }
.section { color: green; }
p[class=section] { color: blue; }
<p>Words Words Words</p>
<p class="section">Words Words Words</p>
<div class="section">Words Words Words</div>
<p class="nothing">words Words Words</p><br/>