确定 CSS 特异性得分
Determining CSS Specificity Score
如何计算这些声明块的特异性分数:
body div main section div ul li p strong span a {}
特异性=1*11=11
并且
.someClass {}
特异性 = 10 * 1 = 10
那么,第一个会赢吗?
A selector's specificity is calculated as follows:
- 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
Selectors inside the negation pseudo-class are counted like any other,
but the negation itself does not count as a pseudo-class.
Examples:
* /* 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 */
Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.
现在我会尽量说清楚它的实际实现方式。 IE。 10 个 htmls 标签不等于一个 class,更像这样:
id : class : tag : pseudo-elements
第一个例子:
body div main section div ul li p strong span a {}
特异性:0 : 0 : 11 : 0
第二个例子:
.someClass {}
特异性:0 : 1 : 0 : 0
11 个元素将获胜,而不是一个 class。更高层总是赢,所以即使超过 1000 classes 也永远不会打败 id(无论如何,使用 id 的样式是相当糟糕的做法)。
不要忘记级联。如果发生冲突,稍后在源文件中声明的具有相同特性的样式将获胜。除了 !important
.
之外,内联样式总是会胜出
如何计算这些声明块的特异性分数:
body div main section div ul li p strong span a {}
特异性=1*11=11
并且
.someClass {}
特异性 = 10 * 1 = 10
那么,第一个会赢吗?
A selector's specificity is calculated as follows:
- 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
Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class.
Examples:
* /* 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 */
Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.
现在我会尽量说清楚它的实际实现方式。 IE。 10 个 htmls 标签不等于一个 class,更像这样:
id : class : tag : pseudo-elements
第一个例子:
body div main section div ul li p strong span a {}
特异性:0 : 0 : 11 : 0
第二个例子:
.someClass {}
特异性:0 : 1 : 0 : 0
11 个元素将获胜,而不是一个 class。更高层总是赢,所以即使超过 1000 classes 也永远不会打败 id(无论如何,使用 id 的样式是相当糟糕的做法)。
不要忘记级联。如果发生冲突,稍后在源文件中声明的具有相同特性的样式将获胜。除了 !important
.