CSS:了解选择器的优先级/特异性 [英] CSS: Understanding the selector's priority / specificity

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

问题描述

我想了解 CSS 选择器如何处理属性冲突,如何选择属性而不是另一个属性?

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?

推荐答案

只需折腾一个链接到CSS 2.1规范本身,以及浏览器如何 来计算特异性:

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第6.4.3节


一个选择器的特异性计算如下:

A selector's specificity is calculated as follows:


  • 如果声明是from是一个'style'属性而不是一个规则一个选择器,否则为0(在HTML中,元素的style属性的值是样式表规则,这些规则没有选择器,因此a = 1,b = 0,c = 0和d = 0。 )

  • 计数选择器中的ID属性数量(= b)

  • 计算选择器中其他属性和伪类的数量= c)

  • 计算选择器中元素名称和伪元素的数量(= d)

  • 特异性仅基于表单的选择器。特别地,即使id属性被定义为ID,形式[id = p33]的选择器也被计数为属性选择器(a = 0,b = 0,c = 1,d = 0)

  • count 1 if the declaration is from is a 'style' attribute rather than a rule with a selector, 0 otherwise (= a) (In HTML, values of an element's "style" attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)
  • count the number of ID attributes in the selector (= b)
  • count the number of other attributes and pseudo-classes in the selector (= c)
  • count the number of element names and pseudo-elements in the selector (= d)
  • The specificity is based only on the form of the selector. In particular, a selector of the form "[id=p33]" is counted as an attribute selector (a=0, b=0, c=1, d=0), even if the id attribute is defined as an "ID" in the source document's DTD.

将四个数字abcd连接在一起(具有大基数的数字系统) / p>

Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the specificity.

如果特殊性相等,则 CSS 2.1第6.4.1节开始起作用:

If the specificities are equal, then CSS 2.1 Section 6.4.1 comes into play:



  1. 最后,按指定的顺序排序:如果两个声明具有相同的权重,起源和特异性,则后者指定胜。导入样式表中的声明被视为样式表本身的任何声明之前。


注这是说风格是什么时候定义的,而不是当它被使用。如果类 .a .b 具有相等的特异性,无论哪一个在样式表中最后定义< 胜出。 < p class =ab> ...< / p> < p class =ba> 。< / p> 将根据 .a .b

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:了解选择器的优先级/特异性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆