參考了2 link,有了些結論:
1, http://ponzmd.javaeye.com/blog/84973 到底谁说了算?CSS 样式优先级判断
2, http://www.w3.org/TR/CSS21/cascade.html#specificity Calculating a selector's specificity
/
到底谁说了算,可以依据下面几个原则:
CSS 样式定义多了,常常出现显示效果与预期不一致的情况。其中很大一部分原因在于起作用的样式。
1。多个选择器可能会选择同一个元素,有3个规则,从上到下重要性降低:
!important的用户样式
!important的作者样式
作者样式
用户样式
浏览器定义的样式
2。CSS 样式的特殊性权重——谁有分量,谁说了算。
CSS 规范为不同类型的选择器定义了特殊性权重,特殊性权重越高,样式会被优先应用。
权重设定如下:
html选择器,权重为1;
类选择器,权重为10;
id选择器,权重为100;
这里还有一种情况:在html标签中直接使用style属性,这里的style属性的权重为1000;
即如下情况:
#x34y {color:red}
<. p id=x34y style="color:green"> 优先选择style=""设定的样式。
其他类型的,大家看看例子就明白了。
例子:
h1{color:blue} 权重为1
p em{color:yellow} 权重为2
.warning{color:red} 权重为10
p.note em.dark{color:grag} 权重为22
#main{color:black} 权重为100 这里还有一种情况:
权重一样时如何处理?权重一样时就另说了。看看下面的就明白了。
3。CSS 样式的层叠原则——谁离我近,谁说了算。
当权重一样时,会采用“层叠原则” 后定义的会被应用。
如:p{color:yellow}
p{color:red}
作用到这里 <. p >我的什么颜色呢?< /p>
结果会是red的。
4。CSS 样式的特殊标记——谁有特权,谁说了算。
如果有人看不顺眼,非得要自己说了算,那可以搞点特权,如下即可
p {color:blue !important;}
加上!important;可将自己权重设为最高。
如果你要问两个!important;设定的样式,那个样式说了算,我说你为什么不自己试试看看呢!
///
6.4.3 Calculating a selector's specificity
A selector's specificity is calculated as follows:
- 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.
Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the specificity.
Some examples:
* {} /* a=0 b=0 c=0 d=0 -> specificity = 0,0,0,0 */
li {} /* a=0 b=0 c=0 d=1 -> specificity = 0,0,0,1 */
li:first-line {} /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
ul li {} /* a=0 b=0 c=0 d=2 -> specificity = 0,0,0,2 */
ul ol+li {} /* a=0 b=0 c=0 d=3 -> specificity = 0,0,0,3 */
h1 + *[rel=up]{} /* a=0 b=0 c=1 d=1 -> specificity = 0,0,1,1 */
ul ol li.red {} /* a=0 b=0 c=1 d=3 -> specificity = 0,0,1,3 */
li.red.level {} /* a=0 b=0 c=2 d=1 -> specificity = 0,0,2,1 */
#x34y {} /* a=0 b=1 c=0 d=0 -> specificity = 0,1,0,0 */
style="" /* a=1 b=0 c=0 d=0 -> specificity = 1,0,0,0 */
<HEAD>
<STYLE type="text/css">
#x97z { color: red }
</STYLE>
</HEAD>
<BODY>
<P ID=x97z style="color: green">
</BODY>
In the above example, the color of the P element would be green. The declaration in the "style" attribute will override the one in the STYLE element because of cascading rule 3, since it has a higher specificity.
///