评分和排名特异性规则
我的样式表中有两个相互竞争的规则:
#parent > div {
color: blue;
}
#child {
color: red;
}
这是相关的 HTML:
<div id="parent">
<div id="child">What color is this text?</div>
<div>This should just be blue</div>
<div>Also should be blue</div>
</div>
为什么 #child
是蓝色而不是红色?
我不确定我是否正在应用评分系统正确。我是这样做的:
- 规则 #1 有一个 id 和一个标签,所以它的分数是
[0, 1, 0, 1]
- 规则 #2 只有一个 id,所以它的分数是
[0, 1, 0, 0]
- 因此规则 #1 获胜,并且它是蓝色的
但这似乎对我来说是错误的 - 第一个规则匹配多个元素;第二条规则只能匹配一个!那么第二条规则不是更具体吗?
I have two competing rules in my stylesheet:
#parent > div {
color: blue;
}
#child {
color: red;
}
Here's the relevant HTML:
<div id="parent">
<div id="child">What color is this text?</div>
<div>This should just be blue</div>
<div>Also should be blue</div>
</div>
Why is #child
blue and not red?
I'm not sure if I'm applying the scoring system correctly. Here's how I did it:
- rule #1 has an id and a tag, so its score is
[0, 1, 0, 1]
- rule #2 has only an id, so its score is
[0, 1, 0, 0]
- therefore rule #1 wins, and it's blue
But this seems wrong to me -- the first rule matches multiple elements; the second rule can only match one! So isn't the second rule more specific?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一点也不。仅仅因为选择器匹配较少的元素并不能使其更加具体。
选择器匹配是按元素而不是按规则进行的。由于有一个更具体的选择器与您的元素
#child
匹配,即#parent > div
,该规则优先,仅此而已。这看起来确实违反直觉,但这就是它的工作原理。解决此问题的一种方法是将
#parent
添加到第二条规则中:Not at all. Just because a selector matches fewer elements doesn't make it more specific.
Selector matching is done on a by-element basis, not a by-rule basis. Since there's a more specific selector that matches your element
#child
, which is#parent > div
, that rule takes precedence, and that's it.It does seem counter-intuitive, but that's just how it works. One way around this is to add
#parent
to your second rule: