CSS is all about cascading, and understanding the rules of which style wins is key for every beginner! π
Hereβs how CSS decides which rule to apply when there are conflicts:
1οΈβ£ Importance
Styles marked with !important
trump everything else.
Example:
color: red !important; /* This will always win! */
2οΈβ£ Specificity
The more specific the selector, the higher priority.
- Universal (
*
) and tag selectors (e.g.,div
) are weakest. - Classes (
.example
) are stronger. - IDs (
#example
) are even stronger. - Inline styles (e.g.,
style="color:blue"
) beat them all (except!important
).
3οΈβ£ Source Order
When two rules have the same specificity, the one written later in the code wins.
Example:
p { color: red; }
p { color: blue; } /* This will apply because it's written later. */
Quick Tip π
If you’re unsure which rule applies, use the browser’s DevTools (Inspect Element) to see the cascade in action!
Master these, and you’ll write clean, predictable styles in no time. Happy coding! π¨β¨
Leave a Reply