Decoding CSS selector priority/specificity
P粉715274052
P粉715274052 2023-10-19 22:58:19
0
2
413

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?

P粉715274052
P粉715274052

reply all(2)
P粉852114752

In order, 1 is the lowest specificity and 5 is the highest specificity. https://youtu.be/NqDb9GfMXuo Demo details will be displayed.

P粉384366923

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 .bdefinition order.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!