CSS Specificity

CSS Specificity

Specificity is what you use to determine which bit of styling will “win” when there are conflicts. It’s all about how specific your styling is in defining what elements it should be applied to.

There are five different levels of specificity, with most important at the top:

  • !important
    • Wherever this is, it wins
    • It’s BAD. Avoid. It makes a mockery of any other css rules, and makes your css v hard to read / debug.
  • Inline styling
    • (use of the Style=”” attribute within an html element)
  • Id selector
    • !! Remember, this means that your html element has an Id, and you are writing styling which will only apply to that one html element with its own unique Id
      • This means your css will not be reusable!
    • Class, pseudo-class or attribute selector
    • Element or pseudo-element selector
  • So, if there is some styling which uses a level higher up the tree, it will win
  • If there are two pieces of styling at the same level, this is how you decide which will win:
    • Whichever one uses the most selectors at that level will win
    • So, div > ul > li > p will beat div > p
    • If they use the same number, then the one defined most recently (eg lower in the file) will win
  • Notes:
    • css-tricks.com uses a numbering system to represent the above levels, eg (0,1,0,3,0)
    • The universal selector (*) has no specificity value (0,0,0,0,0)
    • Pseudo-elements (e.g. :first-line) get 0,0,0,0,1 unlike their psuedo-class brethren which get 0,0,0,1,0
    • The pseudo-class :not() adds no specificity by itself, only what’s inside it’s parentheses.
    • The !important value appended a CSS property value is an automatic win. It overrides even inline styles from the markup. The only way an !important value can be overridden is with another !important rule declared later in the CSS and with equal or great specificity value otherwise. You could think of it as adding 1,0,0,0,0 to the specificity value.

More here (this was where I made these notes from): http://css-tricks.com/specifics-on-css-specificity/

Also more here: http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.