The CSS cascade resolves conflicts by comparing importance (!important), origin (user vs author), specificity, and source order. More specific selectors win; if specificity ties, later rules take precedence. Edge cases like !important and inline styles can override expectations; test computed styles.
How does the CSS cascade determine which styles are applied?
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
Overview
The cascade is the algorithm browsers use to combine styles from different sources. When multiple rules target the same element, CSS evaluates them using a four-step hierarchy: importance, origin, specificity, and order of appearance.
Step | Concept | Explanation |
|---|---|---|
1 | Importance | Rules marked with |
2 | Origin | Inline styles > author stylesheets > user stylesheets > browser defaults. |
3 | Specificity | More specific selectors take precedence (e.g., IDs > classes > elements). |
4 | Source Order | When all else is equal, the rule defined last in the CSS wins. |
p { color: blue; } /* element selector */
.text { color: green; } /* class selector */
#intro { color: red; } /* ID selector */
p { color: purple !important; } /* overrides all */
Result: The !important rule wins even though the ID selector is more specific. Without !important, the ID selector would take priority.
Best Practices
- Keep selectors consistent and avoid unnecessary complexity.
- Minimize use of
!important; rely on proper structure and specificity instead. - Understand how frameworks (e.g., Bootstrap) use cascade layers and resets.
- Use the browser’s ‘Computed Styles’ panel to debug cascading conflicts.
The cascade is like a courtroom: importance is the judge, specificity is the lawyer’s strength, and source order is who speaks last.
Practical scenario
A component library sets button styles, and your app needs overrides. The cascade order determines whether your app styles actually win.
Common pitfalls
- Assuming later rules always win without checking specificity.
- Overusing
!importantand making future overrides impossible. - Forgetting inline styles beat most stylesheet rules.
Lower specificity is easier to maintain but may lose to library styles. Use DevTools to inspect the winning rule in the computed panel.