How do CSS selectors with higher specificity override others?

LowIntermediateCss
Preparing for interviews?

Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.

Quick Answer

Specificity determines which CSS rule takes precedence when multiple rules target the same element. Each selector type contributes a different weight, and higher specificity overrides lower ones regardless of source order (except when !important is used).

Answer

Overview

When multiple CSS rules apply to the same element, the browser resolves conflicts using specificity. Specificity is calculated based on the selector’s type — IDs, classes, attributes, and element names each contribute differently to its weight.

Selector Type

Example

Specificity Weight

Inline Styles

style='color: red;'

1000

ID Selectors

header

100

Class, Attribute, or Pseudo-class

.btn, [type='text'], :hover

10

Element or Pseudo-element

div, p, ::before

1

Universal or Inherited

  • or inherited styles

0

Specificity scoring system

Example: Competing Rules

CSS
p { color: blue; }       /* 1 */
.text { color: green; }  /* 10 */
#intro { color: red; }   /* 100 */
                  

In this case, #intro (specificity 100) overrides .text (10) and p (1), resulting in red text.

Special Case: !important

The !important flag overrides all other specificity rules except inline styles with !important. Overusing it can lead to maintenance headaches, so use it sparingly and strategically.

Calculation Formula
Specificity is commonly represented as a four-part value (a,b,c,d):

      • a – Inline styles (1 if present)
      • b – Number of IDs
      • c – Number of classes, attributes, pseudo-classes
      • d – Number of element names and pseudo-elements

Example: #nav .menu li:hover → (0,1,2,1) → Specificity = 121.

Best Practices

      • Keep selectors simple and avoid chaining too many elements or classes.
      • Use class-based selectors for scalability instead of IDs.
      • Reserve !important for utility classes or third-party overrides.
      • Refactor conflicting styles rather than stacking specificity.

Still so complicated?

Think of specificity like a ranking system — inline styles are presidents, IDs are generals, classes are officers, and element selectors are soldiers. The higher rank always wins the battle for styling control.

Summary
      • Specificity determines which CSS rule is applied when conflicts occur.
      • Calculated based on selector type weights.
      • Higher values override lower ones.
      • Use classes over IDs for maintainable and modular codebases.
Similar questions
Guides
1 / 30