I know that if two CSS rules apply to the same element, the more specific one will have priority:
p { color:red; } /* Todos os "p"s serão vermelhos... */
.umaClasse { color:yellow; } /* ...exceto os que possuem "umaClasse", que serão amarelos */
#umID { color:green; } /* ...exceto o "umID", que será verde. */
And intuitively I realize that "the element with ID X" is more specific than "all elements with class Y". In the case of the class, okay, there may be more elements with class Y than elements with the Z tag (if the same class applies to several different tags), but anyway how is something defined by the programmer I understand that should have priority.
I also know that if two "equal" rules exist (i.e. with the same selector), the one that was set then will take precedence. And recently trying answering another question my tests have shown that the same applies to media queries (ie if there are two rules equally applicable, it is worth more than it appeared later).
My confusion starts in cases where there is more than one criterion in the same selector (type p.umaClasse
) - which I imagine only increases its specificity (ie you must have the tag p
and the umaClasse
class). On the other hand, I do not see a difference between p#umID
or simply #umID
, since there is only one element with this ID, both selectors should be equal, but it ends up having priority:
p#a { color: blue; }
#a { color: red; }
<p id="a">Teste</p>
Another confusing situation is when you select one element within the other:
.a div p span { color:red; }
div .d { color:green; }
.b .c span { color:blue; }
<div class="a">
<div class="b">
<p class="c">
<span class="d">Teste</span>
</p>
</div>
</div>
I noticed that the last rule took precedence and, if it is commented, the first rule takes precedence. Why?
- If we did a top-down analysis, the first one should be the most specific (since the second and third would pick descendants of any element, not just% s of% s with class
div
); - If we did a bottom-up analysis, the second should be the most specific (since the first and third take any
a
, and second only those with thespan
class) ; - The first one has a longer string, but the third one establishes more classes. Is this the dominant factor? And if we mixed classes with ids, what would it look like?
I also tried to think of an example with pseudo-classes or attributes, but it has already confused my head even more ...
There is a simple way to determine which of the two CSS rules will have priority? Whether the hierarchy of elements is taken into account or not, etc.