Tuesday, March 18, 2008

CSS selectors precedence (and ways to waste time)

If you ever wondered how CSS selectors work and how to figure out precedence of CSS rules, read the CSS specificity spec and CSS selectors spec.

The gist of if? Think of it as four values: a,b,c,d.
  • a= count 1 if the declaration is from is a 'style' attribute rather than a rule with a selector, 0 otherwise (= a) (In HTML, values of an element's "style" attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)
  • b= count the number of ID attributes in the selector (= b)
  • c= count the number of other attributes and pseudo-classes in the selector (= c)
  • d= count the number of element names and pseudo-elements in the selector (= d)
Oh, and I've learnt this the hard way: don't start your IDs or CSS class names with a number. FF/IE simply ignore them. I suppose there is a spec somewhere for this as well ... sigh...

No comments: