CSS Specificity

 

有时候对于页面元素设置了样式,可为什么页面的显示没有匹配上呢? because specificity

CSS 的选择符是有权重的,当不同的选择符的样式设置有冲突时,浏览器会采用权重高的选择符设置的样式。

    规则:

 

  HTML标签的权重是1

  Class 的权重是10

  Id 的权重是100

  内敛的权重是1000
 

例如: p 的权重是 1 ,“ div em{} ”的权重是 1+1=2 ,“ strong  .demo{} ”的权重是 10+1=11

#test  .red{} ”的权重是 100+10 = 110

 

Specificity hierarchy 权重等级

1.       内敛: Inline styles (Presence of style in document)  An inline style lives within your XHTML document. It is attached directly to the element to be styled. E.g. <h1 style="color: #fff;">

2.       ID 选择器 IDs (# of ID selectors)
ID is an identifier for your page elements, such as #div .

3.       类选择器 Classes, attributes and pseudo-classes (# of class selectors).
This group includes .classes , [attributes] and pseudo-classes such as :hover , :focus etc.

4.       元素与伪元素 Elements and pseudo-elements (# of Element (type) selectors).
Including for instance :before and :after . 

 

 

例子:

<style>
  span{font-size:40px;color:green}
  .test{color:red}
</style>
</head>
<span class="test">CSS权重测试</span>
 

 

Span 权重是 1 .test 的权重为 10 ,所以“ CSS权重测试 ”的 显示颜色red

 

 

注意:如果 CSS 选择符权重相同,那么样式会遵循就近原则,哪个选择符最后定义,就采用哪个选择符的样式。

 

 

参考资料:

http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值