我得到两个h1的红色背景色。对于第一个 h1,ID 具有最高优先级,对于第二个 h1,内联具有最高优先级。为什么?
#myid { background-color: pink; }
.main h1 { background-color: red; }
div h1 { background-color: blue; }
h1 { background-color: green; }
<!-- the background-color expected
to be pink for the following h1 -->
<div class="main" id="myid">
<h1>This is paragraph one!</h1>
</div>
<!-- the background-color expected
to be brown for the following h1 -->
<div style="background-color:brown;" class="main" >
<h1>This is paragraph two!</h1>
</div>
这两者都与样式是直接应用于元素还是父元素有关。
在这两种情况下,你的直觉对于外部div.main
元素都是正确的。但是,有些规则适用于h1
,虽然不太具体,但直接应用于h1
,因此它们优先于适用于div
的更具体的规则。
无论继承规则的特殊性如何,直接目标元素的样式将始终优先于继承的样式。
https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity#Directly_targeted_elements_vs._inherited_styles
您不是将背景应用于h1
元素,而是应用于其父元素。考虑到这一点,这里没有特异性,因为我们只考虑应用于h1
的规则,如果没有规则,我们考虑继承(应用于父元素的样式,由子元素继承(。此外,background
不是默认继承的值,因此即使您没有指定要h1
的背景,继承也不会在此处适用。
因此,在这种情况下,红色将始终获胜,因为它是直接应用于h1
的具有最高特异性的规则。
粉红色背景存在,但它被位于其顶部的 H1 的红色背景隐藏。
如果向 #myid 样式添加一些填充,您将在H1的红色周围看到粉红色轮廓