I want to understand how CSS selectors handle property conflicts. How to select one property over another?
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: pink; }
<div id="my_id" class="my_class">hello</div>
How does selector priority work?
In order, 1 is the lowest specificity and 5 is the highest specificity. https://youtu.be/NqDb9GfMXuo Demo details will be displayed.
I'll add a link to the CSS 2.1 specification itself, and how browsers should calculate specificity:
CSS 2.1 Section 6.4.3:
If the properties are the same, CSS 2.1 Section 6.4.1 comes into play:
Please note that what is discussed here is the time of style definition, not the time of use. If classes
.a
and.b
have the same specificity, the one last defined in the style sheet takes precedence.
and...
have the same style, based on...
.a
and.b
definition order.