在CSS规则中重复类名称是否会增加其优先级? [英] Does repeating a classname in a CSS rule increase its priority?

查看:60
本文介绍了在CSS规则中重复类名称是否会增加其优先级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个< div> :

<li class="menu-item"> ... </li>

有人可以告诉我是否可以使用 li.menu-item.menu-item.menu-item {...} 来使此CSS规则具有更高的优先级吗?

Could somebody tell me if I can use li.menu-item.menu-item.menu-item { ... } to make this css rule has a higher priority?

更新:

下面是说明这一点的代码:

Here is the codes to illustrate this:

<ul>
    <li class="menu-item dark">Item 1</li>
    <li class="menu-item dark">Item 2</li>
    <li class="menu-item dark menu-item-special">Item 3</li>
    <li class="menu-item dark">Item 4</li>
</ul>

.menu-item.dark {
    background: #333;
    height: 40px;
    line-height: 40px;
    margin-bottom: 10px;
}
.menu-item-special.menu-item-special.menu-item-special {
    background: blue;
}

还有一个jsfiddle: http://jsfiddle.net/wenjiehu/6hycnscy/

There is also a jsfiddle: http://jsfiddle.net/wenjiehu/6hycnscy/

您可以看到项目3"的背景颜色是蓝色.

You can see that the background colour of "Item 3" is blue.

推荐答案

这不是一个好习惯,因为您必须按照规范进行确认,但有趣的是它将产生效果.

This isn't good practice because you have to go to the spec to confirm it, but interestingly enough it will have an effect.

我不相信,但是如果您查阅CSS规范,没有什么排除重复类以提高特异性:

I didn't believe it, but if you consult the CSS spec, there is nothing that precludes repeating a class to increase specificity:

  • 如果声明的来源是"style"属性,而不是带有选择器的规则,则计数为1;否则为0(否则== a)(在HTML中,元素的"style"属性的值是样式表规则.这些规则具有没有选择器,因此a = 1,b = 0,c = 0和d = 0.)
  • 计算选择器中ID属性的数量(= b)
  • 计算选择器(= c)中其他属性和伪类的数量
  • 计算选择器(= d)中元素名称和伪元素的数量

在您的示例中:

.menu-item.dark {} 
/* a=0 b=0 c=2 d=0 -> specificity = 0,0,2,0 */
li.menu-item-special.menu-item-special.menu-item-special
/* a=0 b=0 c=3 d=0 -> specificity = 0,0,3,1 */

所以后者实际上是赢家!

So that latter actually wins!

要添加更多上下文,请按特定性规则进行分层,因此,在 #foo 下,规则,!important :

To add more context, specificity rules are hierarchical, so below #foo beats your rule, as does !important:

#foo
/* a=1 b=0 c=0 d=0 -> specificity = 0,1,0,0 */
li.menu-item-special.menu-item-special.menu-item-special
/* a=0 b=0 c=3 d=0 -> specificity = 0,0,3,1 */

注意:我仅在Chrome和IE8上对此进行了测试.由于其不确定的性质,某些浏览器的行为可能有所不同.

Note: I've only tested this on Chrome and IE8. Because of its undefined nature some browsers may act differently.

这篇关于在CSS规则中重复类名称是否会增加其优先级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆