CSS 继承 vs CSS 特异性

CSS inheritance vs CSS specificity

我在大学计算机科学系从事 Web 开发 Class,老师问 class:"Why a class selector rule was getting applied over a tag selector rule (see example code)?"。 我回答说这是因为 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>