本文介绍了了解CSS选择器的优先级/特性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解 将根据的定义顺序, code>。


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?

解决方案

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.

这篇关于了解CSS选择器的优先级/特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:19