Specificity & Cascade
Understand which conflicting rule wins.
Syntax
/* id beats class beats element */When multiple rules target the same element, the browser decides using specificity:
- Inline styles are strongest.
- Then ids.
- Then classes, attributes, and pseudo-classes.
- Then element and pseudo-element selectors.
If two rules have equal specificity, the one written last wins. This ordering is the cascade.
Example
Loading editorβ¦
Press Run to see the result.
When to use it
- A developer debugs why a button's color isn't changing and discovers an ID selector (#btn) overrides the .btn class rule because of higher specificity.
- A designer uses !important sparingly on a utility class .text-center to ensure it overrides any other alignment rules in third-party stylesheets.
- A team adopts a specificity hierarchy (element < class < ID) as a coding convention so rules predictably override each other as component depth increases.
More examples
Specificity score comparison
Shows three competing rules with increasing specificity scores; the ID rule wins regardless of source order.
/* Specificity: 0-0-1 (element) */
p { color: gray; }
/* Specificity: 0-1-0 (class) β wins over element */
.intro { color: #2965f1; }
/* Specificity: 1-0-0 (ID) β wins over class */
#hero-text { color: #e05c00; }Cascade and source order tie-break
When two rules share the same specificity, the one declared last in the stylesheet wins via the cascade.
/* Both have specificity 0-1-0; last declaration wins */
.box { background-color: lightblue; }
.box { background-color: lightyellow; }
/* Later external sheet also wins on same specificity */
@import url('base.css'); /* declares .box background */Overriding with !important carefully
Reserves !important only for utility overrides like .hidden, leaving normal layout rules to resolve via specificity.
/* Utility override β use sparingly */
.hidden { display: none !important; }
/* Everything else through normal specificity */
.card { display: flex; }
#sidebar .card { display: block; }
Discussion