CSS Cascade and Specificity Explained
Understand how the CSS cascade chooses a style using origin, importance, specificity, scope and source order, with beginner examples.
How the cascade chooses a style
When several CSS declarations target the same property on an element, the browser resolves them through the cascade. The result depends on where a declaration comes from, whether it is marked important, selector specificity and, when those factors tie, source order.
Compare selector specificity
An ID selector has greater specificity than a class selector, and a class selector has greater specificity than a type selector. Keep selectors straightforward so later changes stay easy to understand.
p { color: #334155; }
.note { color: #14532d; }
#intro-note { color: #7c2d12; }
If all three selectors match the same paragraph, the ID rule wins on specificity. The !important flag changes the cascade and should be reserved for cases where you control the competing styles.
Inheritance and source order
Some properties, such as color and font-family, are inherited by child elements. If declarations have equal cascade priority and specificity, the one that appears later wins.
When equal selectors compete
If two declarations have the same cascade priority and the same specificity, the later declaration wins for that property:
.notice {
color: #14532d;
}
.notice {
color: #7c2d12;
}
Here, both selectors target the same elements and have equal specificity, so the second color value is used. Adding a more specific selector just to win a conflict can make future styles harder to override.
Understand inheritance
Inherited properties pass from a parent to its children when the child does not have its own winning declaration for that property. For example, a paragraph can inherit its text color from the body. Properties such as margin and padding are not inherited by default.
Use important declarations sparingly
!important changes how declarations are prioritized. It can make normal rules harder to override and can turn a small conflict into a chain of escalating overrides. First check the matching selectors, cascade layers and source order in your browser’s developer tools.
CSS cascade questions
Does the last CSS rule always win?
No. Source order settles a conflict only after the declarations have the same relevant cascade priority and specificity. A rule with higher priority or specificity can win even if it appears earlier.
Why does a child element have the parent’s color?
Some CSS properties, including color, inherit when the child has no winning declaration of its own. Add a rule to the child if it needs a different value.