CSS 继承与 CSS 特异性

标签 css inheritance css-specificity

我在大学计算机科学系的 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/

相关文章:

html - 显示 :inline-block not line oriented 的布局

javascript - 一页上的多个幻灯片

Swift 继承 vs 调用 super

css - 如何确定我的 CSS 选择器从何处被覆盖?时间轴.js

html - !important 被一类子元素覆盖

html - ID 属性的属性选择器是否不如 ID 选择器具体?

javascript - SVG - 在没有图像填充的情况下以圆形为中心的图像

jquery - 侧边栏应该 float 在移动设备的顶部 - 但不是在桌面上

python - 在 Web.py/MIMERender 应用程序中重复类装饰器

python - 使用多重继承保存 Django ModelForm