我想知道 CSS 规则是如何应用于子元素的。
h2
的gray
样式被覆盖了,因为有父级样式.level2 h2
和blue
颜色。
但是 .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/