The Cascade
Overview
The 'Cascade' is the foundational algorithm of CSS. In complex applications, it is incredibly common for multiple conflicting CSS rules to accidentally target the exact same element. For example, a global stylesheet might declare all buttons should be blue, but a component stylesheet declares the 'submit' button should be green. The Cascade determines which rule 'wins' and actually gets painted to the screen based on three strict rules: Importance, Specificity, and Source Order.
Syntax
/*
Example of conflicting rules on the same element: <h1 class="title">
*/
/* Rule 1: Defined at the top of the file */
h1 {
color: black;
}
/* Rule 2: Defined later in the file (Wins due to Source Order) */
h1 {
color: gray;
}
/* Rule 3: Uses a Class (Wins due to higher Specificity) */
.title {
color: blue;
}
/* Rule 4: Uses !important (Wins against almost everything) */
.title {
color: red !important;
}Common Pitfalls
- Abusing
!importantto solve minor layout bugs.!importantviolently rips the rule out of the normal cascade flow. If you use it everywhere, you completely destroy the maintainability of your CSS, making it impossible to override styles gracefully in the future. - Ignoring Source Order. If two selectors have the exact same specificity weight, the one that appears LAST in the final loaded CSS file wins. This is why you must carefully control the order in which you import your stylesheets.
Interview Questions
1. Importance (e.g., !important flags). 2. Specificity (e.g., ID beats Class, Class beats Tag). 3. Source Order (If specificity is identical, the rule declared latest in the CSS file wins).
Real-World Example
Using Source Order safely to create fallback styles for older browsers.
/*
Legacy browsers don't understand oklch colors.
They will parse the first line, then hit the second line, fail, and ignore it.
Modern browsers will parse the first line, then hit the second line, and overwrite the first!
*/
.box {
background-color: #ff0000; /* Fallback for IE11 */
background-color: oklch(60% 0.2 20); /* Modern high-gamut color */
}Check Your Knowledge
Test your understanding of The Cascade with these quick questions.