ProgramGuru

CSS Specificity and !important

CSS Specificity and !important

Specificity helps the cascade choose between competing selectors, but it is not the only cascade rule.

What you’ll learn

  • Compare type, class and ID specificity.
  • Predict which ordinary declaration wins.
  • Avoid unnecessary !important overrides.

Understand the concept

Within comparable cascade declarations, an ID selector outranks a class selector, and a class selector outranks a type selector. A useful mental model is ID–class–type counts. Selector lists and functional pseudo-classes have additional rules; this lesson starts with the most common cases.

!important changes declaration importance and can override ordinary declarations, but it is not simply another specificity number. Prefer simple classes over escalating specificity fights.

Visualize the relationship

p → type.note → class#hero → IDWithin comparable rules, ID outranks class, and class outranks type.
Within comparable rules, ID outranks class, and class outranks type.

Class beats element

Both selectors match the same paragraph.

HTML

<p class="highlight">Class selector wins.</p>

CSS

.highlight { color: #1d4ed8; }
p { color: #dc2626; }

Rendered output

Class selector wins.

Observe: The paragraph stays blue, even though the element selector appears later.

ID beats class

An ID selector wins this ordinary-rule conflict.

HTML

<p id="hero" class="highlight">ID selector wins.</p>

CSS

#hero { color: #7c3aed; }
.highlight { color: #0f766e; }

Rendered output

ID selector wins.

Observe: The text appears purple. The later class rule has lower specificity.

Explain the result

Compare declarations in the correct cascade context first. Only then does selector specificity become decisive; source order breaks ties of equal specificity.

Compare the two examples: identify the selector, each changed property, and which visible part of the output proves that the CSS took effect.

Common mistakes to avoid

  • Do not treat specificity as a simple sum that ignores selector categories.
  • Avoid using !important as the first fix for confusing CSS.

Try it yourself

Replace #hero with .highlight, then add a second class rule and predict the winning color.

Before changing the code, predict what will change. Then verify by checking the rendered result.

Check your understanding

Under ordinary declarations in the same cascade origin and layer, which selector is typically more specific?
Choose one answer. You can try again.

Answer and explanation

#hero

An ID selector has greater specificity than a class or type selector.

What you should remember

Keep specificity predictable with clear classes and minimal overrides.

Revisit the rendered examples if the rule still feels abstract. Change one declaration at a time so you can connect cause and effect.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: CSS Colors (HEX, RGB, HSL) →