When multiple CSS rules match the same element, the browser decides which one to apply based on specificity. Specificity is like a score that depends on the type of selector you use (inline, ID, class, element, etc.). The rule with the higher specificity wins.
Understanding specificity helps you predict which styles will apply and avoid confusion when styles “don’t work” as expected.
!important can override normal specificity, but should be used carefully.| Priority | Example | Description |
|---|---|---|
| Inline style | <h1 style="color: pink;"> |
Highest priority, directly applied with the style attribute |
| ID selectors | #navbar |
Second highest priority, based on the unique id of an element |
| Classes & pseudo-classes | .test, :hover |
Target elements using reusable class names or states |
| Attributes | [type="text"] |
Match elements by attribute values |
| Elements & pseudo-elements | h1, ::before, ::after |
Lowest priority, target HTML tags and their pseudo-elements |
Browsers assign a “weight” to selectors. A simplified priority order is:
#id).class, [attr], :hover)p, h1, ::before)When selectors conflict, the rule with higher specificity wins. If specificities are equal, the rule that appears later in the CSS file wins due to the CSS Cascade.
/* Same element targeted by element, class, and ID selectors */
div {
background-color: lightgray;
color: black;
}
.box {
background-color: blue;
color: white;
}
#special {
background-color: green;
color: white;
}
<!-- Watch which background color finally applies -->
<div class="box">Class selector (.box)</div>
<div id="special" class="box">ID selector (#special) - highest specificity</div>
In the second <div>:
div selector applies a base style..box selector overrides it with a blue background.#special selector overrides both with a green background.Because ID selectors have higher specificity than class or element selectors, the final background color becomes green.
When selectors conflict, the one with the higher priority wins. For example:
#id beats .class.class beats element!important RuleThe !important declaration can override all normal specificity rules, including inline styles. However, it should be used sparingly because it makes your CSS harder to maintain.
/* Forces this style to win, even over more specific selectors */
.box {
background-color: red !important;
}
If a .box element is targeted by other selectors (even IDs or inline styles), the background-color: red !important; rule will usually win.
Overusing !important can lead to specificity “wars” where you keep adding more !important just to override previous rules. It’s better to structure your CSS carefully instead.
!important only when absolutely necessary (e.g., utility helper classes).p) and a class selector (.highlight). See which style wins.!important on a class and see how it affects other selectors.