CSS · Layout and visual systems

How does CSS specificity work?

MediumspecificityselectorscascadeUpdated Oct 2026
Quiz this track

Short answer

Specificity is a three-part weight: IDs, then classes, attributes and pseudo-classes, then element types and pseudo-elements. Inline styles beat selector-based rules, and !important changes the cascade.

Specificity is compared as a tuple, not a single number. The selector with the higher ID count wins. If those are equal, the higher class count wins. If those are equal, the higher type count wins. Inline styles and !important sit outside this normal comparison.

css
#nav .item a { color: red; }
.item a { color: blue; }
a { color: green; }
The weights are roughly 1-1-1, 0-1-1 and 0-0-1, so the first rule wins.

What counts

  • IDs add to the first part
  • Classes, attributes and pseudo-classes such as :hover add to the second part
  • Element types and pseudo-elements such as ::before add to the third part
  • :where() always contributes zero specificity
  • :is(), :not() and :has() take the specificity of their most specific argument

The universal selector and combinators add nothing. A long descendant selector is not more specific than a short one unless it adds IDs, classes or types.

Chasing a conflict with more selectors or !important makes the stylesheet harder to change. Prefer flatter selectors, lower-specificity utilities such as :where(), or cascade layers.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1How is specificity calculated?
  2. 2How specific is :is() and :where()?
  3. 3Where do inline styles sit in the cascade?
  4. 4How would you override a rule without increasing specificity?

Say it in the interview

I think of specificity as three buckets: IDs, then classes and pseudo-classes, then elements and pseudo-elements. You compare buckets left to right, so one ID beats any number of classes. Inline styles and important declarations sit outside normal selector specificity. To avoid a specificity war, I use flatter selectors, :where() to zero out weight, or cascade layers.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live CSS mock interview and get scored feedback on depth, clarity and confidence.