Most of us have learnt CSS by trial & error & that includes me, it only takes minor success to develop strong interest in what we work on daily basis. However, having said that I strongly believe just know-how of any technology or concept does not cut it. One should make an effort to find out the logic behind the things that set our trial & error standards.
There’s one that I am absolutely in love with & i.e. CSS Specificity. We all have spent countless hours trying to override previously written CSS declarations with the new ones because the deadlines are catching up & we are moreover frustrated because we don’t know how does CSS decides which rule takes precedence over which.
TODAY I’LL HELP YOU ALL KISS/KILL THIS MONSTER!
Consider following 2 CSS declarations:
p{ color:red; value=1 } ulp { color:red; value=2 }
It is quite clear to all of us that the latter declaration will takes precedence & win since from the look of it appears MORE SPECIFIC. It is after all, about survival of the fittest.
What do those values mean by the way? They are specificity weightage & that is the deciding factor when it comes to which rule wins! Each selector has predefined value & with the help of a simple cheat sheet we can all safely determine what will work & what won’t.
The table is below:
Selector | Specificity value | Example | Reason |
* (Universal Selector) | 0 | * | Not so specific since it targets all elements |
element, pseudo element | 1 | div,span :first-line, :first-letter, :first-child, :last-child | More specific since it targets very specific elements |
class, | 10 | .anyCssClass :hover,:link, :visited, a[href] | Only targets elements when classes & attributes specified |
# (Identifier) | 100 | #myId | this is the most specific since this can occur only once in the page |
inline style (style=””) | 1000 | <divstyle=”float left;”></div> | This is very close to the element you are trying to style & hence carries more weightage |
Time for some action:
ul ol+li (1+1+1)=3
Final value of the declaration above is 3. How? Let me explain
- ul is element. Hence 1
- ol is also an element. Hence 1
- li is obviously an element & yes, 1
We add it all up & get 3. Wasn’t that easy?
Now try & find specificity weightage for following declarations:
- li:first-line
- h1+*[rel=up]
- ul ol li.red
- li.red.level
- .sith
- div p .sith
- #sith
- body #darkside .sith p
Next time, you are stuck with messy CSS & trying to find your way out, bring up this table & start calculating. You surely would have written stronger selector in no time!
Have more questions, shoot those to us.