Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save finalfantasia/909c74fdd9d057720690 to your computer and use it in GitHub Desktop.
Save finalfantasia/909c74fdd9d057720690 to your computer and use it in GitHub Desktop.
Calculating a CSS Selector's Specificity

A selector's specificity is represented by concatenating three numbers: a-b-c (in a number system with a large base), which are calculated as follows:

a = the count of ID selectors in the selector
b = the count of class selectors, attributes selectors, and pseudo-classes in the selector
c = the count of type selectors and pseudo-elements in the selector
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 */

Note: Repeated occurrences of the same simple selector are allowed and do increase specificity.

Source: http://www.w3.org/TR/selectors/#specificity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment