有没有办法将 CSS 规则标记为不太重要,这样即使第一个规则具有更高的具体值,它也不会覆盖后续规则?例如,假设我的 CSS 文件中有以下内容:
#inputDiv input[type="text"]{
width:125px;
}
#differentInput1{
width:25px;
}
#differentInput2{
width:500px;
}
我想要的想法是,div“inputDiv”的子级的所有文本输入字段的宽度均为 125px,除了某些特定的输入会获得其他宽度。问题是第一个声明覆盖了特定项目的声明。
我尝试过以下方法:
有没有什么方法可以简单地说第一个声明中的项目不太重要,并且不应该覆盖任何内容?
没有办法做到这一点,因为它与 CSS 是对立的,就像
!important
一样——做相反的事情同样是滥用行为。 您唯一的选择是依赖选择器的特异性。 例如,您可以使用 inputDiv
的类而不是 ID,以一种不那么麻烦的方式编写此代码。
也许有一种方法可以解决您的问题或回答您的问题,您可以尝试这样的事情
<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>
和关于!重要
的一点解释 css 文件中的!important 用于覆盖直接在 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>
正如其他人指出的那样,您可以通过更明智地选择选择器来避免这些问题。作为最佳实践,请尽可能避免使用 ID,并尝试对任何给定的一组样式仅使用一个或两个选择器。
例如,而不是:
#inputDiv input[type="text"]{
width:125px;
}
#differentInput1{
width:25px;
}
#differentInput2{
width:500px;
}
你可以尝试这样做:
input[type="text"]{
width:125px;
}
.differentInput1{
width:25px;
}
.differentInput2{
width:500px;
}
如果您需要更多的特异性,类似这样的东西也可以:
.inputDiv input[type="text"]{
width:125px;
}
.inputDiv .differentInput1{
width:25px;
}
.inputDiv .differentInput2{
width:500px;
}
最终,您希望整个网站的样式保持一致,因此您不需要如此精细。您可能想研究一下 OOCSS,它非常有助于我编写更轻量级、更具可扩展性的 CSS。
http://coding.smashingmagazine.com/2011/12/12/an-introduction-to-object-oriented-css-oocss/ http://oocss.org/
现在有一种广泛支持的方法可以使规则不那么具体:@layer。
https://developer.mozilla.org/en-US/docs/Web/CSS/@layer
<style>
p {
color: rebeccapurple;
}
@layer type {
.box p {
font-weight: bold;
color: green;
}
}
</style>
<div class="box">
<p>Hello, world!</p>
</div>
<p>
内的文本将是粗体和紫色,而不是粗体和绿色,即使绿色的选择器具有更高的特异性。