【问题标题】:CSS inheritance vs CSS specificityCSS 继承与 CSS 特异性
【发布时间】:2019-10-02 16:43:52
【问题描述】:

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

虽然是对的,但为什么 CSS 特异性是一个不正确的答案?

p {
   color: red;
}

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

【问题讨论】:

  • 假设您的段落有section 类,文本为绿色的原因肯定是由于特殊性。类规则比元素规则更具体,因此元素规则中定义的样式可能会在类规则中被覆盖。 CSS 中的继承与 DOM 层次结构有关。某些样式继承自父元素。
  • 你的回答是对的。如果是&lt;p&gt;&lt;span class="section"&gt;Section&lt;/span&gt;&lt;/p&gt;,那肯定与继承有关,但是……不是!

标签: css inheritance css-specificity


【解决方案1】:

正如我在评论中所说,我相信你是对的: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>

【讨论】:

    猜你喜欢
    • 2017-09-28
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    • 2015-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多