How are the points in CSS specificity calculated

后端 未结 7 1649
萌比男神i
萌比男神i 2020-11-21 05:18

Researching specificity I stumbled upon this blog - http://www.htmldog.com/guides/cssadvanced/specificity/

It states that specificity is a point-scoring system for

7条回答
  •  灰色年华
    2020-11-21 05:54

    The current Selectors Level 4 Working Draft does a good job of describing Specificity in CSS:

    Specificities are compared by comparing the three components in order: the specificity with a larger A value is more specific; if the two A values are tied, then the specificity with a larger B value is more specific; if the two B values are also tied, then the specificity with a larger c value is more specific; if all the values are tied, the two specifities are equal.

    This means that the values A, B and C are completely independent of each other.

    15 classes doesn't give your selector a specificity score of 150, it gives it a B value of 15. A single A value is enough to overpower this.

    As a metaphor, imagine a family of 1 grand parent, 1 parent and 1 child. This could be represented as 1,1,1. If the parent has 15 children, that doesn't suddenly make them another parent (1,2,0). It means that the parent has an awful lot more responsibility than they had with just 1 child (1,1,15). ;)

    The same documentation also goes on to say:

    Due to storage limitations, implementations may have limitations on the size of A, B, or c. If so, values higher than the limit must be clamped to that limit, and not overflow.

    This has been added to tackle the problem presented in Faust's answer, whereby CSS implementations back in 2012 allowed specificity values to overflow into each other.

    Back in 2012, most browsers implemented a limitation of 255, but this limitation was allowed to overflow. 255 classes had an A,B,c specificity score of 0,255,0, but 256 classes overflowed and had an A,B,c score of 1,0,0. Suddenly our B value became our A value. The Selectors Level 4 documentation completely irradiates that problem by stating that the limit can never be allowed to overflow. With this implementation, both 255 and 256 classes would have the same A,B,c score of 0,255,0.

    The problem given in Faust's answer has since been fixed in most modern browsers.

提交回复
热议问题