The Cascade
Cascading
Section titled “Cascading”Cascade means for something to flow from top to bottom like a waterfall. In CSS, this refers to how styles are applied when multiple rules target the same element — the rules are checked from top to bottom, and the most specific or latest rule wins.
If two conflicting rules have the same specificity, the last one declared in the code takes precedence.
Example
Section titled “Example”<style> .title { color: red; }
.title { color: green; }</style>
<p class="title"> Molestie quisque consequat faucibus mattis taciti vehicula ornare maecenas nascetur magnis ligula nec.</p>Molestie quisque consequat faucibus mattis taciti vehicula ornare maecenas nascetur magnis ligula nec.
In the example above, both rules target the same class, .title. Since they have the same specificity, the second rule (color: green) overrides the first.
Specificity
Section titled “Specificity”Specificity describes the “weight” or “strength” of CSS selectors. If multiple rules target the same element, the one with the higher specificity wins — regardless of order (unless the specificity is equal).
Example 1:
Section titled “Example 1:”<style> #example { color: hotpink; } .sample { color: chocolate; } p { color: maroon; }</style>
<p id="example" class="sample">Specificity can be slimy!</p>Output:
Toggle me!
Specificity can be slimy!
The id selector has a higher specificity than both .class and element selectors.
Example 2:
Section titled “Example 2:”<style> .sample { color: chocolate; } p { color: maroon; }</style>
<p class="sample">Specificity can be slimy!</p>Output:
Toggle me!
Specificity can be slimy!
The .class selector overrides the element selector because it has higher specificity.
Specificity Hierarchy
Section titled “Specificity Hierarchy”Here’s the order of selector specificity, from highest to lowest:
- Inline styles (e.g.,
style="color: pink;") - IDs (e.g.,
#navbar) - Classes, pseudo-classes, attribute selectors (e.g.,
.btn,:hover,[type="text"]) - Element and pseudo-element selectors (e.g.,
div,h1,::before)
Summary
Section titled “Summary”- CSS rules “cascade” from top to bottom.
- If two rules have the same specificity, the one lower in the stylesheet wins.
- The rule with higher specificity always overrides lower specificity.
- Use inline styles and
!importantcautiously, as they can make styles harder to manage.