确定CSS特异性得分 [英] Determining CSS Specificity Score

查看:109
本文介绍了确定CSS特异性得分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算这些声明块的特异性得分:

How do I calculate the specificity score for these declaration blocks:

body div主要部分div ul li p强跨度a {}

特异性= 1 * 11 = 11

Specificity = 1*11=11

然后,

.someClass {}

特异性= 10 * 1 = 10

Specificity = 10 * 1 = 10

那么,第一个会赢吗?

推荐答案

W3C规范指出:


选择器的特异性计算如下:

A selector's specificity is calculated as follows:


  • 计算选择器中ID选择器的数量(= a)

  • 计算选择器中的类选择器,属性选择器和伪类的数量(= b)

  • 计算类型选择器和伪类的数量-选择器中的元素(= c)

  • 忽略通用选择器

  • count the number of ID selectors in the selector (= a)
  • count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= b)
  • count the number of type selectors and pseudo-elements in the selector (= c)
  • ignore the universal selector

选择器insid e否定伪类的计数与其他任何伪类
一样,但否定本身不算作伪类。

Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class.

示例:

*               /* a=0 b=0 c=0 -> specificity =   0 */
LI              /* a=0 b=0 c=1 -> specificity =   1 */
UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
\#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
\#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */

将三个数字abc(在基数较大的数字系统中)相加得到

Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.






现在我将尝试弄清楚它是如何实现的。就是10个htmls标签不等于一个类,它更像是这样:


Now I will try to make it clear how it is actually implemented. Ie. 10 htmls tags do not equal one class, it goes more like this:

id:class:tag:伪元素

第一个示例:

body div main section div ul li p strong span a {}

专长: 0:0:11:0

第二个示例:

.someClass {}

特异性: 0:1:0:0

11个元素不会赢得一个类。较高的级别总是会胜出,因此甚至超过1000个课程也不会击败id(反之,使用id的样式实在是一种不好的做法)。

11 elements will win not with one class. Higher tier always wins, so even more than 1000 classes will never beat id (styling with id's is rather bad practice anyway).

不要忘记级联。稍后在源文件中声明的具有相同特异性的样式将获胜。内联样式始终会赢得任何胜利,除了!important

Do not forget about cascade. Styles with the same specificity declared later in source file(s) will win in case of conflict. The inline styles will always win with anything, except of !important.

这篇关于确定CSS特异性得分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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