So when calculating the specificity of some CSS code I came across with something I find contradictory.
According to the "formula" (inline > id > class > elements) I made the calculations for the couple of lines ahead:
(1) p.b {color: red} Specificity: (0,0,1,1)
(2) .a>.c {color: black} (0,0,2,0)
Since (2) has 2 classes, its specificity is higher than (1) and therefore the browser should go for black instead of red, which happens exacly the other way around.
Can anyone give me some insight on what I'm doing wrong?
HTML CODE:
/* Specificity: (0,0,1,1) */
p.b {
color: red
}
/* (0,0,2,0) */
.a>.c {
color: black
}
<div class="a">
<div class="c">
<p class="b">Parágrafo 2</p>
</div>
</div>
Regarding the second paragraph: out of your two selectors, the .a > .c
selector only directly applies to the parent <div class="c">
element. Its styles are inherited if any other selectors don't override them. but the p.b
selector is the only one of the two that directly applies to the child <p>
element with the text in it, so it takes precedence. As another poster said, the specificity rules don't apply unless two selectors are targeting the same element. Here they are targeting a parent and a child. When deciding the styling for the child, the child's own selectors will always win over styles inherited from a parent.