CSS子选择器的优先级高于类选择器?

发布于 2024-11-30 20:44:34 字数 383 浏览 0 评论 0原文

我有以下 HTML:

<div class="form-square">
     <div class="seven-col">
        Hello World!
      </div>
</div>

和以下 CSS:

div.form-square > div {
    padding: 50px;
}

.seven-col {
    padding: 0;
}

Firefox 和 Firebug 使用两个 CSS 规则中的第一个。为什么“div.form-square > div”的优先级高于更具体的“.seven-col”?

I have the following HTML:

<div class="form-square">
     <div class="seven-col">
        Hello World!
      </div>
</div>

And the following CSS:

div.form-square > div {
    padding: 50px;
}

.seven-col {
    padding: 0;
}

Firefox and Firebug is using the first of the two CSS rules. How come "div.form-square > div" has higher precedence than ".seven-col" which is more specific?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

灵芸 2024-12-07 20:44:34

div.form-square> div 由 1 个类选择器 + 2 个类型选择器(加上一个子组合器)组成。

.seven-col 由 1 个类选择器组成。

类选择器的数量是相等的,因此比较是在类型选择器中完成的。第一个选择器有更多类型选择器,因此更具体。

特异性基于整个事物中每种选择器的数量,而不是最右侧组合器右侧的部分。

(注意:第一个示例也具有 CSS 2 所谓的子选择器,但这不计入特异性,并且描述了元素之间的关系而不是元素的功能,这可能是 CSS 3 将其重命名为子组合器的原因)。

div.form-square > div consists of 1 class selector + 2 type selectors (plus a child combinator).

.seven-col consists of 1 class selector.

The number of class selectors is equal, so the comparison is done in type selectors. The first selector has more type selectors so it is more specific.

Specificity is based on the number of each kind of selector in the entire thing, not for the part on the right hand side of the rightmost combinator.

(NB: The first example also has what CSS 2 calls a child selector, but that doesn't count towards specificity and describes a relationship between elements rather than a feature of an element, which probably why CSS 3 is renaming it to the child combinator).

痴意少年 2024-12-07 20:44:34

正确,第一条规则比第二条更具体,因为仅类选择器的优先级相当低。

Correct, the first rule is more specific than the second, because a class only selector has a fairly low priority.

爱你不解释 2024-12-07 20:44:34

.seven-col 有 1 个类 = +1

div.form-square > div 有 2 个元素和 1 个类 = +3

使用此 CSS 特异性计算器检查一下:
http://www.suzyit.com/tools/specificity.php

.seven-col has 1 class = +1

div.form-square > div has 2 elements and 1 class = +3

Check it out with this CSS specificity calculator:
http://www.suzyit.com/tools/specificity.php

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