评分和排名特异性规则

发布于 2025-01-05 23:00:57 字数 753 浏览 0 评论 0原文

我的样式表中有两个相互竞争的规则:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜访吸血鬼 2025-01-12 23:00:57

但这似乎对我来说是错误的——第一个规则匹配多个元素;第二条规则只能匹配一个!那么第二条规则不是更具体吗?

一点也不。仅仅因为选择器匹配较少的元素并不能使其更加具体。

选择器匹配是按元素而不是按规则进行的。由于有一个更具体的选择器与您的元素 #child 匹配,即 #parent > div,该规则优先,仅此而已。

这看起来确实违反直觉,但这就是它的工作原理。解决此问题的一种方法是将 #parent 添加到第二条规则中:

#parent > div {
    color: blue;
}

#parent > #child {
    color: red;
}

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?

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:

#parent > div {
    color: blue;
}

#parent > #child {
    color: red;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文