CSS Specificity


🔹 What Is CSS Specificity?

CSS Specificity determines which CSS rule is applied when multiple rules target the same element. It defines the priority of a selector.

If multiple styles apply to the same element, the browser uses the rule with the highest specificity value.


🔸 1. Specificity Hierarchy (from lowest to highest)

Selector Type Specificity Value
Universal (*) 0,0,0
Element (div, p) 0,0,1
Class (.class) 0,1,0
Attribute ([type]) 0,1,0
Pseudo-class (:hover) 0,1,0
ID (#id) 1,0,0
Inline styles 1,0,0 (but higher priority)
!important Overrides all (but avoid overuse)

🔸 2. Example: Basic Specificity Comparison

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

.text {
  color: green;      /* Specificity: 0,1,0 */
}

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

Final color: red due to higher specificity of #main.


🔸 3. How Specificity Is Calculated

Example:

div#main .text:hover {
  color: orange;
}

Breakdown:

  • ID selector → 1

  • Class + Pseudo-class → 2

  • Element → 1

Specificity: 1,2,1


🔸 4. Inline Styles & !important

Inline style:

<p style="color: purple;">Hello</p>

Inline styles have very high specificity: 1,0,0

Use of !important:

p {
  color: orange !important;
}

Overrides all other rules, even if specificity is lower.


🔸 5. Equal Specificity – Which One Wins?

If specificity is the same, the later rule in the CSS file wins.

p {
  color: red;
}

p {
  color: green;
}

Final color: green (last rule wins)


Practice Questions

Q1. Set color using an element selector (h1).

Q2. Override with a class selector (.title).

Q3. Override again using an ID selector (#heading).

Q4. Use an inline style to set background color.

Q5. Add !important to a font-size rule.

Q6. Use both class and pseudo-class in a selector.

Q7. Add an attribute selector to style checkboxes.

Q8. Write a selector that combines element + ID + class.

Q9. Add multiple conflicting styles and determine which wins.

Q10. Use same specificity in two rules and reorder to test precedence.


Go Back Top