What is CSS specificity and how is it calculated?

· Category: HTML & CSS

Short answer

Specificity is the algorithm browsers use to decide which CSS rule applies when multiple selectors target the same element. It is calculated based on the components of the selector.

How it works

Specificity is often represented as a tuple of four numbers: (inline styles, IDs, classes/attributes, elements). A higher value in any column beats a lower overall total in columns to the right.

Example

/* Specificity: 0,0,1,0 */
.button { color: blue; }

/* Specificity: 0,1,0,0 */
#submit { color: red; }

/* Specificity: 0,0,2,0 */
.nav .button { color: green; }

/* Specificity: 0,0,1,1 */
button.button { color: purple; }

Why it matters

Understanding specificity prevents unexpected style overrides and reduces reliance on !important. When specificity grows out of control, developers often resort to overly complex selectors or !important, which creates technical debt.