I'd like to understand how CSS
selectors work with properties collisions, how a property is selected instead of another one?
div {
background-color:red;
}
div.my_class {
background-color:black;
}
div#my_id {
background-color:blue;
}
body div {
background-color:green;
}
body > div {
background-color:orange;
}
body > div#my_id {
background-color:white;
}
<html>
<body>
<div id="my_id" class="my_class">hello</div>
</body>
</html>
For someone this could be obvious, but not for me!
Does exist some guide or link where I can finally understand how selector priority works?
In order, 1 is the lowest specificity and 5 is the highest. https://youtu.be/NqDb9GfMXuo will shown details to demo it.
You can refer the full answer here Mozilla documentation
Start from the most specific: id selectors > class selectors > type selectors(normal h1, p tag and so on..) !important always wins, but it is considered a bad practice.See the link above.
The best way is to experiment with it:
CSS:
Here's a test case.
I'll just toss in a link to the CSS 2.1 spec itself, and how browsers are supposed to calculate specificity:
CSS 2.1 Section 6.4.3:
If the specificities are equal, then CSS 2.1 Section 6.4.1 comes into play:
Note that this is talking about when the style is defined, not when it is used. If classes
.a
and.b
have equal specificity, whichever is defined last in the stylesheet(s) wins.<p class="a b">...</p>
and<p class="b a">...</p>
will be styled identically, based on the definition order of.a
and.b
.What you are interested in is specificity.
Firebug is a great tool to help inspect this. But other browsers also have built in tools for inspecting the applied CSS rules.