Archive for December 2012

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

Difference between p.div, div p and div > p

Friday, December 28, 2012 · Posted in ,

Here the div can be interchangeably used for both class and id, but of course you have to use p#div instead of p.div. I am giving the example with <p> element, but it is true for any other element as well.


Let's say our html file is like this:

  <title>CSS Selector</title>
   <style type="text/css">
    p.para2 { color:green; }
   <p>First Paragraph under class1.</p>
   <p class="para2">Second paragraph under class1 with class para2.</p>

The output of this will be like this:

First Paragraph under class1.
Second paragraph under class1 with class para2.

So it only selects those <p> elements with class name "para2"

Powered by Blogger.