The selectors .parent-class p
and p.child-class
have exactly the same CSS specificity, both have 1 tag selector and 1 class selector. The selector that comes later in code will apply.
CSS lower specificity rules override higher specificity rules
-
04-06-2022 - |
Question
I have this simple CSS code:
p.child-class {
color: red;
}
.parent-class p {
color: green;
}
html:
<div class="parent-class">
<p class="child-class"></div>
</div>
The selector .parent-class
is being applied instead of the higher specificity selector p.child-class
. Why is that?
Here's a Fiddle.
EDIT
I understand that both have the same specificity. In that case, how can I increase the specificity of the child's class if I can't edit the parent's class code?
Solution
OTHER TIPS
Your both rules having different meaning
.parent-class p
this specify the rule for p
which is inside the container having class .parent-class
p.child-class
this specify the rule for p
which has the class child-class
As mentioned, they have the same specificity, the the order of the rules is significant.
Adding .parent-class
will change the specificity
.parent-class p.child-class {
and then the order won't matter.
You could use !important
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow