Skip to main content

How is specificity calculated? What does the specificity formula look like?

Specificity is calculated as a numeric "weight" of the selector, made up of four digits. The browser builds the number using the formula:

javascript
[a, b, c, d]

Where:

DigitWhat it countsExamples
ainline stylesstyle=""
bID selectors#header
cclasses, attributes, pseudo-classes.box, [type="text"], :hover
dtag selectors and pseudo-elementsdiv, p, ::after

How it's calculated

The selector is broken down into parts, and each part increases one of the digits.

For example:

SelectorSpecificity
div0,0,0,1
.text0,0,1,0
#main0,1,0,0
header .menu li0,0,1,2 (1 class + 2 tags)
#main .menu li0,1,1,1
style="color:red"1,0,0,0

How they're compared

The comparison goes digit by digit, from left to right:

  1. first a (inline) is compared
  2. if equal, b (id)
  3. if equal, c (classes)
  4. if equal, d (tags)

The rule with the higher number in the first digit that differs is the one that applies.


Important exceptions

  • !important does not take part in the formula, but overrides everything except another !important
  • * (the universal selector) adds no weight
  • combinators (>, +, ~, a space) also do not affect the weight

Summary of the formula

Specificity = [a, b, c, d], where:

  • a: inline
  • b: ID
  • c: classes, attributes, pseudo-classes
  • d: tags and pseudo-elements

This formula determines which rule wins when styles conflict.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

How is specificity calculated? What does the specificity formula look like?: CSS Interview Question