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. */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
MDN — cascade order, including scope
Keep exploring
- CSS · Guide
Selectors: choosing what to styleMatch the element you mean before adjusting its appearance.
- CSS · Guide
The box modelUnderstand where an element’s width really comes from.