QA
Beginner LevelCSS & Modern Layouts

How does CSS specificity and the cascade determine which styles are applied?

❓ Interview Prompt: Explain the CSS cascade algorithm, specificity scoring rules, and how conflicts between selectors are resolved.

When multiple CSS rules target the same element, the browser resolves conflicts using the Cascade Algorithm in this priority order:

1
Origin & Importance: !important > inline styles > author stylesheets > browser defaults.
2
Specificity Score: Calculated as a 3-part tuple (ID, Class, Element):
•
ID selectors (#header): (1, 0, 0) — highest weight
•
Class/Attribute/Pseudo-class (.nav, [type="text"], :hover): (0, 1, 0)
•
Element/Pseudo-element (div, ::before): (0, 0, 1)
•
Universal selector (*): (0, 0, 0) — no weight
3
Source Order: When specificity is equal, the rule declared last in the stylesheet wins.

Code Implementation Example

css
/* Specificity: (0, 0, 1) — Element selector */
p { color: blue; }

/* Specificity: (0, 1, 0) — Class selector (wins over element) */
.intro { color: green; }

/* Specificity: (1, 0, 0) — ID selector (wins over class) */
#hero-text { color: red; }

/* Specificity: (0, 1, 1) — Combined selector */
p.intro { color: purple; }

/* Avoid: !important overrides everything */
.override { color: orange !important; }
💡Specificity score comparison across different selector types.
🎯 Interview Key Takeaway

Specificity is scored as (IDs, Classes, Elements). Higher specificity always wins regardless of source order.

#Specificity#Cascade#Selectors#Beginner
Back to all CSS & Modern Layouts Questions→

More CSS & Modern Layouts Interview Questions

Beginner LevelCSS & Modern Layouts

What is the CSS Box Model and how do content, padding, border, and margin interact?

Beginner LevelCSS & Modern Layouts

What are the differences between display: block, inline, inline-block, flex, and grid?

Beginner LevelCSS & Modern Layouts

How does CSS Flexbox work and what are its key container and item properties?