html - 应用于子元素的 CSS 规则顺序

标签 html css

我想知道 CSS 规则是如何应用于子元素的。

h2gray 样式被覆盖了,因为有父级样式.level2 h2blue颜色。

但是 .level1 h2 的应用方式不同。

请看下面的例子。

.level1 h2 {
  color: green;
}
.level2 h2 {
  color: blue;
}
h2 {
  color: gray;
}
<div class="level1">
  <div class="level2">
    <h2>test</h2>
  </div>
</div>

最佳答案

都是关于specificity的和继承。

The notion of a “cascade” is at the heart of CSS (just look at its name). It ultimately determines which properties will modify a given element. The cascade is tied to three main concepts: importance, specificity and source order. The cascade follows these three steps to determine which properties to assign to an element. By the end of this process, the cascade has assigned a weight to each rule, and this weight determines which rule takes precedence, when more than one applies.

如果两个选择器具有相同的特异性,它还取决于样式表中的顺序

    .level2 h2 {
        color: blue;
    }
    .level1 h2 {
        color: green;
    }

    h2 {
        color: gray;
    }
     <div class="level1">
        <div class="level2">
           <h2>test</h2>
        </div>
     </div>

来源: https://www.smashingmagazine.com/2010/04/css-specificity-and-inheritance/

关于html - 应用于子元素的 CSS 规则顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37435156/

相关文章:

html - 应用圆形 CSS 边框和不透明效果时图像无法正确显示

html - 您可以在没有 javascript 的情况下启用禁用的按钮吗?

html - 下拉子li背景中的父ul颜色

javascript - 如何链接 P5.js 设置并使用 html canvas 进行绘制?

javascript - jquery - 使用图像的 attr() 时未定义 src

css - 如何在 bool 玛级别组件中实现分词并设置左右等宽?

javascript - 试图将许多单选按钮显示为列 - 得到奇怪的输出

html - 如何防止文本在插入的元素下换行?

html - 颜色 : transparent is not working in Internet Explorer

javascript - 检查屏幕上是否存在 html 元素