如何理解Css Specificity

除了浮动特性,CSS Specificity特性也是样式表中较为难理解的概念之一.在通常情况下,你认为一些应该应用到元素的CSS规则为何浏览器没有应用到.为了尽量花少 时间去排错,你需要去了解浏览器是如何解释你的样式代码;另外,你还需要系统地理解CSS Specificity特性是如何工作的.类似此类问题大多数原因是在样式表中的另一个位置定义了更特殊的选择器.

Css Specificity虽不简单,然而,还是有办法用简单直观地方式介绍它.

Css Specificity概览

  1. Specificity特性决定哪些CSS规则应用于客户端浏览器.
  2. 优先级是你的CSS规则通常应该不到一些元素的原因,包括你认为应该应用到的。
  3. 每个选择符都有它自身的层级数。
  4. 如果两个选择符属性同时应用于同一个元素,优先级高的生效。
  5. 可分为四种明显的优先级类别:inline style,IDs,classes+attributes,elements
  6. 如你喜欢星球大战的话可看看:CSS Specificity Wars
  7. 如你喜欢纸牌游戏的话可看看:CSS Specificity for Poker Players
  8. 当Speficity值相等时,后来选择符居上。
  9. 当Speficity值不相等时,Speficity值高的选择符生效。
  10. 越具体的选择符越有更高的优先级数
  11. 最后的CSS规则将覆盖任何之前或冲突的CSS规则。
  12. 嵌入式样式的Speficity值高于其它。
  13. ID选择符比属性选择符Speficity值要高。
  14. 你可用IDs去提高选择符的Speficity值
  15. class选择符高于大部分的元素选择符
  16. The universal selector and inherited selectors have a specificity of 0, 0, 0, 0.

另外,!important规则高于一切,慎用;继承的样式属式不参与优先级数值计算,低于其它规则。

因为每种选择符都有它自身的优Speficity值,下面看看具体的计算规则:

  • Inline style(嵌入式样式),即直接写在元素里面,加1,0,0,0,E.g. <h1 style=”color:#fff;”>
  • IDs(ID选择符),加0,1,0,0,E.g.#div
  • classes+attributes(Class选择符、属性选择符和伪类),加0,0,1,0,E.g. .classes、[attributes]、:hover,#focus
  • elements(每个元素或伪元素),加 0,0,0,1。E.g. :firstchild
  • Others(其他选择符),加 0,0,0,0。 E.g. * >

如何计算Speficity值?

  • 记住如何计算Speficity值,“从0开始,加1000给style属性,加100给每个ID选择符,加10给每个属性选择符、Class或 伪类,加1给每个元素名或伪元素。因此
    body #content .data img:hover
    的Speficity值就为:122(0,1,2,2 或0122):100给#content ,10给.data,10给:hover,1给body,1给img.”
  • 另外可选择一种计算方式:计算每个ID选择符(=a),计算每个属性选择符(=b),计算每个元素或伪元素(=c),连接这三个值 a-b-c 即得出Speficity值。
  • 下面有张图可帮助我们更加直观的了解如何计算Speficity值

动手测试

1 * { } 0
2 li { } 1 (one element)
3 li:first-line { } 2 (one element, one pseudo-element)
4 ul li { } 2 (two elements)
5 ul ol+li { } 3 (three elements)
6 h1 + *[rel=up] { } 11 (one attribute, one element)
7 ul ol li.red { } 13 (one class, three elements)
8 li.red.level { } 21 (two classes, one element)
9 style=”” 1000 (one inline styling)
10 p { } 1 (one HTML selector)
11 div p { } 2 (two HTML selectors)
12 .sith 10 (one class selector)
13 div p.sith { } 12 (two HTML selectors and a class selector)
14 #sith 100 (one id selector)
15 body #darkside .sith p { } 112 (HTML selector, id selector, class selector, HTML selector; 1+100+10+1)

About this entry

You’re currently reading “如何理解Css Specificity,” an entry on Jaybird

Published:
8.10.08 / 12pm
Category:
Front-end
Tags:
Css Speficity

原文链接:http://www.smashingmagazine.com/2007/07/27/css-specificity-things- you-should-know/ 翻译:http://www.obird.net/web-standards/%E5%A6%82%E4 %BD%95%E7%90%86%E8%A7%A3css-specificity/

原文地址:https://www.cnblogs.com/yuzhongwusan/p/1779055.html