π What Is the CSS Cascade?
The term cascade refers to the process CSS uses to determine which styles are applied to an element when there are conflicting rules. The browser follows a strict sequence called the cascade order. Mastering this helps you write predictable, conflict-free styles. π§ β¨
π The Cascade Order
CSS resolves conflicts by following three major steps (in this order):
- 1οΈβ£ Importance (Is it marked with !important?)
- 2οΈβ£ Specificity (How strong is the selector?)
- 3οΈβ£ Source Order (Which rule appears last?)
1οΈβ£ Importance β The Highest Priority
If a rule uses !important, it jumps above all normal rules. Importance overrides specificity and source order. β οΈ
Importance Example
p {
color: blue !important;
}
p {
color: red;
}π Final color: blue (because !important wins)
Note
2οΈβ£ Specificity β The Selector Strength
When rules donβt use !important, CSS compares their specificity. Higher specificity wins. If you need a refresher, see your tutorial onSpecificity in CSS. π
Specificity Example
p { color: black; } /* specificity: 0,0,0,1 */
.text { color: blue; } /* specificity: 0,0,1,0 */
#main { color: red; } /* specificity: 0,1,0,0 */π Winner: #main selector (highest specificity)
3οΈβ£ Source Order β Last Rule Wins
When importance and specificity are equal, the rule that appears last in the CSS file wins. πβ‘οΈπ
Source Order Example
p {
color: blue;
}
p {
color: green;
}π Final color: green (because it appears last)
π How All Three Work Together
Cascade Comparison
/* 1. Normal rule */
p { color: black; }
/* 2. Higher specificity */
#title p { color: blue; }
/* 3. !important overrides all */
p { color: red !important; }Final color applied: red π₯ Because !important beats both specificity and source order.
π Cascade Order Summary Table
| Priority Level | Description | Example |
|---|---|---|
| 1οΈβ£ Importance | !important rules override everything else | color: red !important; |
| 2οΈβ£ Specificity | Stronger selectors beat weaker ones | #id > .class > element |
| 3οΈβ£ Source Order | Last declared rule wins when all else is equal | p {color: green} coming later |
π§© Real Example: Putting It All Together
Combined Example
h1 { color: black; }
.title { color: blue; }
#mainTitle { color: orange; }
h1 { color: purple !important; }π― Final color applied: purpleBecause importance outranks specificity & order.
π Best Practices for Working with the Cascade
- Use !important only when absolutely necessary π«
- Write clear, minimal selectors
- Organize your CSS to reduce conflicts
- Understand specificity to avoid over-styling
- Let the cascade work for you, not against you πΏ