Specificity Rules in CSS
In the previous example, both selectors were the same and had the same priority. This means that the property written below won.
There are also situations when several selectors match one page element. In this case, in case of a property conflict, the more specific, i.e., more precise selector, will win. Let's look at the rules of specificity.
Rule number one
Class always wins over tag selector:
<p class="text">text</p>
p {
color: red;
}
.text {
color: green; /* this color will be applied */
}
:
Rule two
Identifier always wins over class:
<p id="elem" class="text">text</p>
.text {
color: red;
}
#elem {
color: green; /* this color will be applied */
}
:
Rule three
All things being equal, the selector with more parts wins. For example, if we have two tag selectors, the one with more tags wins:
<div>
<p>text</p>
</div>
p {
color: red;
}
div p {
color: green; /* this color will be applied */
}
:
If there are two class selectors, the one with more classes specified wins (if there are tag selectors, they do not affect):
<div class="block">
<p class="text">text</p>
</div>
.text {
color: red;
}
.block .text {
color: green; /* this color will be applied */
}
: