search

Home  >  Q&A  >  body text

Learn more about CSS selector priority and specificity

<p>I want to understand how CSS selectors work in property conflicts. How is one attribute selected over another? </p> <p><br /></p> <pre class="brush:css;toolbar:false;">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; }</pre> <pre class="brush:html;toolbar:false;"><div id="my_id" class="my_class">hello</div></pre> <p><br /></p> <p>How does selector priority work? </p>
P粉036800074P粉036800074568 days ago579

reply all(2)I'll reply

  • P粉739706089

    P粉7397060892023-08-23 20:07:38

    In order, 1 is the lowest specificity and 5 is the highest. https://youtu.be/NqDb9GfMXuoDetails will be shown for demonstration.

    reply
    0
  • P粉384244473

    P粉3842444732023-08-23 17:29:30

    I'll just add a link here to the CSS 2.1 specification itself, and how browsers should calculate specificity:

    CSS 2.1 Section 6.4.3:

    If specificities are equal, CSS 2.1 Section 6.4.1 :

    will be used

    Please note that this is discussed when the style is defined, not when used. If the specificities of classes .a and .b are equal, the class last defined in the stylesheet will win. <p class="a b">...</p> and <p class="b a">...</p> will Set in the same style according to the definition order of .a and .b.

    reply
    0
  • Cancelreply