Understand the idea
When several rules set the same property, the cascade determines which declaration wins. A selector matching the element is only the first step.
For ordinary stylesheet rules, origin, importance and cascade layers are considered before selector specificity. When these are equal, specificity is compared; equally specific scoped rules may then be distinguished by proximity to their scope root. Source order resolves a remaining tie. Inline styles, animations and transitions add further precedence rules. For an inherited property with no specified value, the computed value normally comes from the parent; non-inherited properties normally use their initial value.
Read the example
This is a CSS fragment. Put it in a stylesheet and supply the matching HTML described in the exercise.
.message { color: navy; }
p.message { color: purple; }
/* For <p class="message">, the second selector is more specific. */Change it. See why.
Adjust the controls and compare the result with the CSS. Changes stay only in this page’s memory.
A small mistake, explained
What goes wrong
Adding more and more !important declarations hides the reason a rule is losing and makes later changes harder.
How to fix it. Find the crossed-out declaration in the Styles panel. Inspect the winning selector, layer and source rather than guessing.
Try it yourself
Apply both rules to a paragraph. Remove p from the second selector and reverse the order of the rules.
Further reading
W3C — CSS Cascading and Inheritance (new tab)
MDN — cascade order, including scope (new tab)
Keep exploring
- CSS · Guide
Find the source of horizontal overflowFix the oversized element instead of hiding the symptom.
- CSS · Guide
Why a huge z-index can still loseUnderstand the group an element belongs to before raising its number.