Yesterday Chris Coyier kicked off a fun journey of discovery by voicing his surprise that 256 classes would override one HTML ID in a selector:
— Chris Coyier (@chriscoyier) August 15, 2012
The CSS2 Spec allows for this
Although that’s a TON of classes on one element, the spec clearly leaves room for this type of override. From the CSS2 spec (emphasis mine):
A selector’s specificity is calculated as follows:
- 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.)
- count the number of ID attributes in the selector (= b)
- count the number of other attributes and pseudo-classes in the selector (= c)
- count the number of element names and pseudo-elements in the selector (= d)
Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the specificity.
The main source of confusion is that there’s no set number in the spec upon which specificity overrides are defined, and it seems to cause a small deviance in interoperability. It goes without saying that this is a somewhat academic discussion, as one would rarely use 256 classes chained together, if ever.
From Mr. Coyier’s brief period of discovery, we seem to have determined that WebKit and Gecko both use an 8-bit number, or base 256 when determining specificity.
After a little bit of prompting from various devs, we finally got word on Opera’s internals. They use 16-bits, or base 65536:
@ryanseddon and to close the loop: yes, opera uses 16 bits instead of 8. bring on 65536 classes…
— patrick h. lauke (@patrick_h_lauke) August 16, 2012
So there you have it. IDs are much harder to override, but they can still be trumped by particularly long selectors. I suspect we could set up other academic-but-impractical cases using tags, combinators and so forth.