为什么它有更高的css优先级

  • 本文关键字:css 优先级 css
  • 更新时间 :
  • 英文 :


为什么:

.cssform input[type="text"]{ /*width of text boxes. IE6 does not understand this attribute*/
    width: 180px;
    padding-bottom: 5px
}

的优先级高于:

.cssform.wide input[type="text"]{ 
    width: 500px;
    padding-bottom: 5px
}

第一个有一个类和一个元素:(0,0,1,1)第二个有2个类和1个元素:(0,0,2,1)

但是应用了第一种样式(IE8和FF)。为什么会这样呢?

你的html中有错误。您提供的CSS与以下html代码完全匹配:

 <form class='cssform wide'>
  <input type="text" />
 </form>

.cssform.wide input[type="text"]选择器优先级更高。可以在jsfiddle

查看

根据CSS的具体规则,应该采用第二条规则。但是,只有在它符合两个规则的情况下。你可能会应用规则对于输入元素(这对您的情况来说是很自然的),但是您的CSS规则查找wide类元的子代输入元。所以用.cssform input.wide代替.cssform .wide input:

.cssform input.wide[type="text"] {
    width: 500px;
    padding-bottom: 5px
}
.cssform input[type="text"] {
    width: 180px;
    padding-bottom: 5px
} 
HTML:

<html>
<head>
  <link rel="stylesheet" type="text/css" href="style.css" /> 
</head>
<body>
  <form class="cssform">
    <input type="text" />
    <input class="wide" type="text" />
  </form>
</body>

一般选择规则如下:1. <style>中的规则,而不是来自其他来源2. 在首选选择器中具有较多ID属性的规则3.在首选选择器中使用更多其他属性和伪类的规则4.

选择器中具有更多元素名和伪元素的规则

如果不够清楚,您总是可以使用工具检查规则专用性,例如suzyit

最新更新