Determining CSS Specificity Score [duplicate]

巧了我就是萌 提交于 2019-12-25 19:39:14

问题


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

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

Specificity = 1*11=11

and,

.someClass {}

Specificity = 10 * 1 = 10

So, will the first one win?


回答1:


W3C specification states:

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.


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 : pseudo-elements


First example:

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

Specificity: 0 : 0 : 11 : 0

Second example:

.someClass {}

Specificity: 0 : 1 : 0 : 0

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).


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.



来源:https://stackoverflow.com/questions/45672765/determining-css-specificity-score

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!