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):
- Inline styles
- Declarations marked !important
- ID selectors (#)
- Class (.) or pseudo-class(:) selectors
- Element (or type) selectors
- 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.