此文章是在jquery学堂7群(221716837)的群共享里面看到网友【北京-前端-熊猫】整理分享的,觉得对网友们的学习有帮助就第一时间整理分享到JquerySchool网站上。。。
CSS优先级、权重
如何计算
优先级是根据由每种选择器类型构成的级联字串计算而成的. 它不是一个对应相应匹配表达式的权重值.
如果优先级相同,元素最终会应用
CSS 中靠后的声明.
注意: 在文档树中的距离是不会对元素优先级计算产生影响的.(可以看文档中无视DOM树中的距离的例子)
优先级顺序
下列是一份优先级逐级增加的选择器列表:
通用选择器(*)
元素(类型)选择器
类选择器
属性选择器
伪类
ID 选择器
内联样式
事实上,元素还可以从父元素上继承一些样式,如color等属性。这些继承的样式的优先级永远低于元素本身的样式,包括通用选择器
!important 规则是例外
当 !important 规则被应用在一个样式声明中时,该样式声明会覆盖CSS中任何其他的声明, 无论它处在声明列表中的哪个位置. 尽管如此, !important规则还是与优先级毫无关系.使用 !important不是一个好习惯,因为它改变了你样式表本来的级联规则,从而难以调试。
用数字的方式表示CSS优先级比较直观,下面是转换方法:
count the number of ID selectors in the selector (= a)
(用a表示ID选择器出现的次数)
count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= b)
(用b表示class选择器、属性选择器、伪类选择器出现的次数)
count the number of type selectors and pseudo-elements in the selector (= c)
(用c表示标签选择器、伪元素选择器出现的次数)
ignore the universal selector
(忽略通用选择器*)
Selectors inside the negation pseudo-class are counted like any other, but the negation itself does not count as a pseudo-class.
(:not 否定伪类在优先级计算中不会被看作是伪类. 尽管如此, 在计算选择器数量时还是会把伪类当做普通选择器进行计数.)
Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.
比较 a*100+b*10+c 的大小
Examples:
* /* a=0 b=0 c=0 -> specificity = 0 */
LI /* a=0 b=0 c=1 -> specificity = 1 */
UL LI /* a=0 b=0 c=2 -> specificity = 2 */
UL OL+LI /* a=0 b=0 c=3 -> specificity = 3 */
H1 + *[REL=up] /* a=0 b=1 c=1 -> specificity = 11 */
UL OL LI.red /* a=0 b=1 c=3 -> specificity = 13 */
LI.red.level /* a=0 b=2 c=1 -> specificity = 21 */
#x34y /* a=1 b=0 c=0 -> specificity = 100 */
#s12:not(FOO) /* a=1 b=0 c=1 -> specificity = 101 */
参考http://www.w3.org/TR/selectors/#selectors
参考 http://www.w3.org/TR/selectors/#specificity
参考 https://developer.mozilla.org/zh-CN/docs/CSS/Specificity#.3Anot_.E4.BC.AA.E7.B1.BB.E4.BE.8B.E5.A4.96
伪类 伪元素
如果您觉得本文的内容对您的学习有所帮助:
关键字:
css css优先级 css权重