CSS 特异性优先
CSS specificity precedence
两个 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>
您没有将背景应用于 h1
元素,而是应用于其父元素。考虑到这一点,这里没有特殊性,因为我们只考虑应用于 h1
的规则,如果没有规则,我们会考虑继承(应用于子元素继承的父元素的样式)。此外 background
不是默认继承的值,因此即使您没有为 h1
.
指定背景,继承也不会在此处应用
所以在这种情况下,红色总是获胜,因为它是具有最高特异性的规则直接应用到h1
。
这两者都与样式是直接应用于元素还是应用于父元素有关。
在这两种情况下,您的直觉对于外部 div.main
元素都是正确的。但是,有些规则适用于 h1
,虽然不太具体,但直接适用于 h1
,因此它们优先于适用于 div
的更具体的规则.
Styles for a directly targeted element will always take precedence over inherited styles, regardless of the specificity of the inherited rule.
存在粉红色背景,但它被位于其上方的 H1 的红色背景所隐藏。
如果您向 #myid 样式添加一些填充,您将在 H1 的红色周围看到粉红色的轮廓
两个 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>
您没有将背景应用于 h1
元素,而是应用于其父元素。考虑到这一点,这里没有特殊性,因为我们只考虑应用于 h1
的规则,如果没有规则,我们会考虑继承(应用于子元素继承的父元素的样式)。此外 background
不是默认继承的值,因此即使您没有为 h1
.
所以在这种情况下,红色总是获胜,因为它是具有最高特异性的规则直接应用到h1
。
这两者都与样式是直接应用于元素还是应用于父元素有关。
在这两种情况下,您的直觉对于外部 div.main
元素都是正确的。但是,有些规则适用于 h1
,虽然不太具体,但直接适用于 h1
,因此它们优先于适用于 div
的更具体的规则.
Styles for a directly targeted element will always take precedence over inherited styles, regardless of the specificity of the inherited rule.
存在粉红色背景,但它被位于其上方的 H1 的红色背景所隐藏。
如果您向 #myid 样式添加一些填充,您将在 H1 的红色周围看到粉红色的轮廓