css - 用类选择器覆盖 h4 的规则

标签 css

我有以下 html:

<div class="main">
  <div class="container">
      <h4 class="test"> Test </h4>
  </div>
</div>​

以及以下 CSS:

.main .container h4 {
 color: red;   

}
.test {
 color: blue;   
}

为什么 .test 类不覆盖颜色规则?我怎样才能做到这一点?

谢谢

最佳答案

这是一个 specificity问题。

特异性是某个选择器的重要性。在这种情况下,您的第一个声明使用两个类和一个元素。这意味着只有内联样式、#id 或具有更多类的东西可以覆盖它。

如果你想影响类test,我们可以使用.main .container .test,这是3个类,现在覆盖它!

如果两个事物具有相同的特异性,例如,如果您再次使用 .main .container h4,则文档中最后出现的事物将优先。

不管你的特殊性或它在文档中的位置,有一种方法可以覆盖,那就是通过添加 !important 到特定的样式,例如 .test { color :蓝色!重要; }。如果您可以使用上述内容,则不建议这样做,因为这可能会导致 future 出现问题。

可以找到规范here

A selector's specificity is calculated as follows:

  • count 1 if the declaration is from is a 'style' attribute rather than a rule with a selector, 0 otherwise (= a) (In HTML, values of an element's "style" attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)
  • count the number of ID attributes in the selector (= b)
  • count the number of other attributes and pseudo-classes in the selector (= c)
  • count the number of element names and pseudo-elements in the selector (= d)
  • The specificity is based only on the form of the selector. In particular, a selector of the form "[id=p33]" is counted as an attribute selector (a=0, b=0, c=1, d=0), even if the id attribute is defined as an "ID" in the source document's DTD.

Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the specificity.

关于css - 用类选择器覆盖 h4 的规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13362033/

相关文章:

html - 为什么我的按钮 float 在包含元素上方?它与 Bootstrap 相关吗?

html - Bootstrap 独立输入焦点颜色

php - 如何在div中加载CKEditor?

html - 仅突出显示表格单元格中的文本

html - 使框的大小包装内容

html - 'middle' 和更大视口(viewport)上的 Fat bootstrap header ?

javascript - 按下按钮时的 Jquery 移动切换按钮数据主题

firefox - 不使用 'all' 的多个 css3 过渡类型

html - 带有变换的样式文本

html - 鼠标悬停时图像变暗