How are the points in CSS specificity calculated

Sam picture Sam · May 11, 2010 · Viewed 22.6k times · Source

Researching specificity I stumbled upon this blog - http://www.htmldog.com/guides/cssadvanced/specificity/

It states that specificity is a point-scoring system for CSS. It tells us that elements are worth 1 point, classes are worth 10 points and IDs are worth 100 points. It also goes on top say that these points are totaled and the overall amount is that selector's specificity.

For example:

body = 1 point
body .wrapper = 11 points
body .wrapper #container = 111 points

So, using these points, I expect the following CSS and HTML to result in the text being blue:

Why is the text red when 15 classes would equal 150 points compared to 1 ID which equals 100 points?

Apparently the points aren’t just totaled; they’re concatenated. Read more about that here - http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html

Does that mean that the classes in our selector = 0,0,15,0 OR 0,1,5,0?

(my instincts tell me it’s the former, as we KNOW the ID selector’s specificity looks like this: 0,1,0,0)

Answer

Faust picture Faust · Aug 13, 2012

Pekka's answer is practically correct, and probably the best way to think about the issue.

However, as many have already pointed out, the W3C CSS recommendation states that "Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity." So the geek in me just had to figure out just how large this base is.

It turns out that the "very large base" employed (at least by the 4 most commonly-used browsers*) to implement this standard algorithm is 256 or 28.

What this means is that a style specified with 0 ids and 256 class-names will over-ride a style specified with just 1 id. I tested this out with some fiddles:

So there is, effectively, a "point system," but it's not base 10. It's base 256. Here's how it works:

(28)2 or 65536, times the number of ids in the selector
+ (28)1 or 256, times the number of class-names in the selector
+ (28)0 or 1, times the number of tag-names in the selector

This isn't very practical for back-of-the-envelop exercises to communicate the concept.
That's probably why articles on the topic have been using base 10.

***** [Opera uses 216 (see karlcow’s comment). Some other selector engines use infinity — effectively no points system (see Simon Sapin’s comment).]

Update, July 2014:
As Blazemonger pointed out earlier in the year, webkit browsers (chrome, safari) now appear to use a higher base than 256. Perhaps 216, like Opera? IE and Firefox still use 256.