D DevBrainBox

CSS Specificity

CSS

What is CSS Specificity?

CSS specificity is a system of weights and ranks used by the browser to decide which CSS rule to apply when multiple rules target the same element.

More specific rules override less specific ones, regardless of where they appear (unless !important is used).

Specificity Value System

Each CSS selector is assigned a specificity score, made of 4 levels (A, B, C, D):

LevelSelector TypeWeight
AInline styles1000
BID selectors (#id)100
CClass, attribute, pseudo-class (.class, [attr], :hover)10
DElement and pseudo-elements (div, p, ::before)1

Example Specificity Scores

/* D = 1 */
p {
  color: blue;
}

/* C = 10 */
.text {
  color: green;
}

/* B + C = 110 */
#main .text {
  color: red;
}

/* A = 1000 (highest) */
style="color: orange;"

The higher the score, the stronger the rule.

  • color: orange (inline) wins over red
  • #main .text (110) beats .text (10)
  • .text (10) beats p (1)

!important Overrides Everything\

p {
  color: black !important;
}

This will override all other rules even if their specificity is higher, unless another !important rule is even more specific.

SelectorSpecificity
div1
.class10
#id100
style=""1000
!importantOverrides all

Tips to Avoid Specificity Issues

  • Avoid using too many nested or overly specific selectors
  • Use class selectors over IDs for styling
  • Use !important only when absolutely necessary

On this page