The calculation of CSS Selector's Specificity

Saturday, December 29, 2012 · Posted in , ,

A few days earlier I came to know about selector's specificity. I always worked with the idea that if I choose a close class or id it will be more specific and override others. Well, this worked as I tend to define more classes and id's as it gives me more control. But I got stuck at last in a simple scenario. My little knowledge wasn't enough to understand why it wasn't working. I could make it work other way, but I wanted to solve the problem. That's how I came to know how Selector specificity works.

Josh Lee wrote a nice answer to this question. I knew that how it works, but didn't really know how specificity is determined real time. So, here is how it is done.

There are four things that you need to look at think these as a, b, c, d

1. For inline stylesheet a=1, otherwise 0
2. b has the value of the number of ID element
3. c has the value of the number of other attributes and pseudo-classes i the selector
4. d has the value of the number of element and pseudo-elements in the selector

Now if you want to calculate specificity you use these values in this order a b c d. Let's see a few examples considering none of these are inline styles.

p { XXX }      ---  here d=1 as there is only one element in the selector. Othes are 0 so specificity is 0001

#content li { XXX } --- here b=1 and d=1. Specificity 0101

.class1 em { XXX } --- c=1, d=1. Specificity 0011

ul li { XXX } --- d=2. Specificity 0002

I believe you get the idea. This is why if you use id element it will override class elements.
For inline styles a=1. So specificity is 1000 which will always override external stylesheet.

Now consider the following--

<ul class="ulclass">
  <li class="liclass">LI1</li>

You can access the <li> element by .ulclass li, .liclass, li.liclass

You may think that .liclass or li.liclass is more specific, but that's not the case. Calculate their specificity
.ulclass li --- Specificity 0011
.liclass --- Specificity 0010
li.liclass --- Specificity 0011

So, it is clear that .liclass won't be used. But if you use both .ulclass li and li.liclass, the one lower in order will  override the other one as their specificity is same.

I hope you won't have any problem with calculating CSS specificity anymore.

Leave a Reply

Powered by Blogger.