Modern CSS

Selectors, Specificity, and Cascade

Understand how CSS targets elements, how specificity works, and how the cascade decides which declaration is applied.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

Understand how CSS targets elements, how specificity works, and how the cascade decides which declaration is applied. This hands-on tutorial focuses on practical implementation of selectors, specificity, and cascade concepts.

Selectors, Specificity, and Cascade

CSS is a rule engine. You write selectors, but the browser decides which declaration wins based on matching, order, and specificity.

The Cascade in Plain English

The browser evaluates styles in this order:

  1. Find all rules that match the element.
  2. Compare importance and specificity.
  3. If specificity is tied, the later rule wins.

Common Selector Types

p {
  color: slategray;
}

.notice {
  color: royalblue;
}

#hero-title {
  color: crimson;
}

.card .title {
  font-weight: 700;
}
  • element selectors are the weakest
  • class selectors are stronger and ideal for components
  • id selectors are very strong and usually best avoided in app styling
  • descendant selectors should stay short and readable

Specificity Example

.button {
  background: gray;
}

header .button {
  background: purple;
}

.button.primary {
  background: seagreen;
}

If an element has class="button primary" inside header, .button.primary is usually the better pattern because it stays component-oriented.

Why !important Is a Smell

!important skips normal conflict resolution. It can be useful in rare utility cases, but it often creates harder overrides later.

Prefer:

  • better class naming
  • lower nesting
  • clearer component boundaries

Maintainable Rules

  • Use classes for UI patterns.
  • Keep selectors shallow.
  • Avoid chaining too many ancestors.
  • Let source order work for you when specificity is equal.

Quick Rule of Thumb

If a selector reads like a sentence, it is probably too specific.

Next Step

Continue to Box Model and Display to understand how elements size themselves and participate in layout.