CSS Specificity and Cascade

Specificity determines which CSS rule applies when multiple rules target the same element.

Specificity Hierarchy

Inline styles have highest specificity (1,0,0,0).

IDs have high specificity (0,1,0,0).

Classes, attributes, and pseudo-classes (0,0,1,0).

Elements and pseudo-elements have lowest (0,0,0,1).

More specific selectors override less specific ones.

/* Element selector - specificity: 0,0,0,1 */
p {
  color: black;
}

/* Class selector - specificity: 0,0,1,0 */
.text {
  color: blue;
}

/* ID selector - specificity: 0,1,0,0 */
#main {
  color: green;
}

/* Combined - specificity: 0,1,1,1 */
#main .text p {
  color: red;
}

/* Inline style wins - specificity: 1,0,0,0 */
/* <p style="color: purple;"> */