有没有办法将CSS规则标记为不太重要,这样即使第一个规则具体更高,它也不会覆盖后续规则?例如,假设我的CSS文件中包含以下内容:
#inputDiv input[type="text"]{
width:125px;
}
#differentInput1{
width:25px;
}
#differentInput2{
width:500px;
}
Run Code Online (Sandbox Code Playgroud)
我想要的想法是所有作为div"inputDiv"的子节点的文本输入字段的宽度为125px,除了某些特定输入获得一些其他宽度.问题是第一个声明会覆盖特定的项声明.
我尝试过以下方法:
有没有办法简单地说第一个声明中的项目不太重要,不应该覆盖任何东西?
Exp*_*lls 15
没有办法做到这一点,因为它与CSS的对立方式!important是相同的- 相反的做法就像滥用一样.您唯一的选择是依赖选择器特异性.inputDiv例如,通过使用类而不是ID,您可以以不那么麻烦的方式编写它.
也许是一种解决您的问题或回答您的问题的方法,您可以尝试这样的方法
( http://jsfiddle.net/6aAF5/ )
<div class="inputDiv big"> BIG</div>
<div class="inputDiv middle"> MIDDLE</div>
<div class="inputDiv small"> small</div>
<p>
<div class="inputDiv"> normal</div>
</p>
<style type="text/css">
.inputDiv {
background-color:green;
width:200px;
height:20px;
}
.inputDiv.big {
background-color:red;
width:400px;
}
.inputDiv.middle {
background-color:lime;
width:100px;
}
.inputDiv.small {
background-color:orange;
width:50px;
}
</style>
Run Code Online (Sandbox Code Playgroud)
以及关于 !important 的一些解释
!important 在 css 文件中用于覆盖直接在 html 中定义的样式。这意味着如果你有
<div class="isItImportant" style="background-color:red;width:100px;height:100px;"></div>
<style type="text/css">
/* this changes the styling */
.isItImportant {
background-color:green !important;
}
/* this doesn't change anything */
.isItImportant {
background-color:fuchsia;
}
</style>
Run Code Online (Sandbox Code Playgroud)
( http://jsfiddle.net/6aAF5/2/ )