我对输入框的 CSS 优先级有疑问。正在应用 96%
的宽度,而根据优先规则应应用 auto
宽度。如果我应用 !important
,就会应用我想要的样式。然而,这不是我想要解决问题的方式。
我有一个以这种方式实现的输入框
<fieldset>
<label>Search</label>
<input type="text" class="standard-size"> <!-- Referring to this -->
</fieldset>
并受这 2 个 CSS 声明的影响:
fieldset input[type=text] {
width: 96%;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
border: 1px solid #BBBBBB;
height: 20px;
color: #666666;
-webkit-box-shadow: inset 0 2px 2px #ccc, 0 1px 0 #fff;
-moz-box-shadow: inset 0 2px 2px #ccc, 0 1px 0 #fff;
box-shadow: inset 0 2px 2px #ccc, 0 1px 0 #fff;
padding-left: 10px;
background-position: 10px 6px;
margin: 0;
display: block;
float: left;
margin: 0 10px;
}
.standard-size {
width: auto ;
}
根据这个链接: http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/
优先级是这样工作的 (内联样式、ID、类、元素)。左边的数字在右边的任何数字之前。
以我为例: fieldset input[type=text] 转换为 (0,0,0,2) 因为 fieldset 和 input 是 2 个元素 和 .standard-size 转换为 (0,0,1,0) 因为 .standard-size 是一个 CSS 类
(0,0,1,0) 应该优先于 (0,0,0,2),因为 1 比 2 更靠左,这使得它更重要。那么为什么96%的宽度会占上风呢?
谢谢
最佳答案
你忘记算上[type=text]
属性选择器了,相当于类选择器(你链接的那篇文章也有提到):
fieldset input[type=text] /* 1 attribute, 2 types -> specificity = (0, 0, 1, 2) */
.standard-size /* 1 class -> specificity = (0, 0, 1, 0) */
虽然属性选择器和类选择器是等效的,但第一个规则中的两个类型选择器导致它超过第二个。
关于html - CSS 优先规则未正确应用于输入框的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20973246/