CSS ยท Module 14 ยท Lesson 8 of 48

CSS Specificity & !important

What is CSS Specificity?

Imagine you are a player in a game. If two referees give you conflicting instructions at the same time, who do you listen to? You listen to the chief referee with the highest authority rank.

In CSS, Specificity is the algorithm the browser uses to decide which styling rule wins when multiple conflicting selectors target the same element. The browser assigns weights to selectors: 1. Inline Styles (placed directly on the element): Authority score = 1000. 2. ID Selectors (e.g., #header): Authority score = 100. 3. Classes, Attributes, and Pseudo-classes (e.g., .card, [type="text"], :hover): Authority score = 10. 4. Elements and Pseudo-elements (e.g., div, p): Authority score = 1.

Why does it matter?

Understanding specificity is critical for debugging why your styles aren't applying. If your text remains black even though you wrote .red-text { color: red; }, it's usually because an ID selector or an inline style has a higher specificity score and is overriding your class style.

Syntax Breakdown

Consider this HTML: <h1 id="title" class="main-header">Heading</h1>
  • h1 { color: red; } โ€” Specificity score: 1.
  • .main-header { color: green; } โ€” Specificity score: 10 (Wins over h1).
  • #title { color: blue; } โ€” Specificity score: 100 (Wins over class).
  • color: purple !important; โ€” Overrides all specificity scores. Use !important as an absolute last resort!
  • Common Mistakes

  • Using ID selectors too often: Because ID selectors have very high specificity, they are difficult to override. Use classes for styling to keep specificity low and manageable.
  • Overusing !important: Sprinkling !important everywhere makes your CSS impossible to maintain. If you have to override an !important rule, you have to write an even more specific !important rule, creating a styling war.
  • Quick Reference

  • Inline โ€” 1000 weight.
  • ID (#) โ€” 100 weight.
  • Class (.) โ€” 10 weight.
  • Element โ€” 1 weight.
  • !important โ€” Absolute override.
  • Your Task
    The h1 is currently blue because the ID selector has higher specificity than the element selector. Force the h1 to render as `red` by adding `!important` to the color property inside the `h1` block.
    index.html
    Type code above to start the lesson.
    Live Preview