Explain CSS specificity and how it works

EasyPhone Screen
GoogleFrontend Engineer
167

What is CSS specificity? How does the browser determine which styles to apply when there are conflicting rules?

1 Answer

145
Top Answer

CSS specificity determines which styles win when there are conflicts.

Specificity Hierarchy (highest to lowest):

  1. Inline styles - style="..." (1,0,0,0)
  2. IDs - #header (0,1,0,0)
  3. Classes, attributes, pseudo-classes - .btn, [type="text"], :hover (0,0,1,0)
  4. Elements, pseudo-elements - div, ::before (0,0,0,1)

Calculating Specificity

/* 0,0,0,1 */
p { }

/* 0,0,1,0 */
.text { }

/* 0,0,1,1 */
p.text { }

/* 0,1,0,0 */
#main { }

/* 0,1,1,1 */
#main p.text { }

Important Notes:

  • !important overrides everything (avoid using it)
  • Later rules win if specificity is equal
  • * selector has 0 specificity
CSSWizard

Share Your Answer

Help others by sharing your knowledge and experience with this question.

Coming soon...

Related Questions

View all

More from Google

View all