My Development Notes


What is the exact order of precedence in CSS?


In CSS, the rule of precedence is actually very simple and straight forward. Those CSS codes which are more specific to a certain situation takes precedence over the less specific code declarations. Now as a general rule of thumb, this is the exact order of precedence (1 the most,6 the least):

  1. Inline styles
  2. Declarations marked !important
  3. ID selectors (#)
  4. Class (.) or pseudo-class(:) selectors
  5. Element (or type) selectors
  6. Universal selector

In short, this is all what you need to understand. Nothing more, nothing less!

Now let’s look at some examples:



<div class="main">
  <h1>This is a topic</h1>
  <div class="sub" id="topic">
      <h1>This is another topic</h1>
  </div>
</div>


.main .sub {
     color : red; /* Rule A */
}
#topic {
     color : blue; /* Rule B */
}

Now look carefully! In the above example the ID (#topic) will take precedence over the class selectors. So color : blue; will take precedence here. Also Rule A won’t work as the main and sub classes have been taken simultaneously where the sub class has been already overridden by the ID(#topic) in this case.

Let’s now take the above example and tweak that a little bit:

.sub {
     color : red !important; /* Rule A */
}
#topic {
     color : blue; /* Rule B */
}

As soon as we used the !important property what happened is that the the class selector took precedence over the ID selector as that’s the general rule.


Leave a Reply

Your email address will not be published. Required fields are marked *