将CSS规则标记为不太重要?

ibr*_*ter 20 css

有没有办法将CSS规则标记为不太重要,这样即使第一个规则具体更高,它也不会覆盖后续规则?例如,假设我的CSS文件中包含以下内容:

#inputDiv input[type="text"]{
    width:125px;
}

#differentInput1{
    width:25px;
}

#differentInput2{
    width:500px;
}
Run Code Online (Sandbox Code Playgroud)

我想要的想法是所有作为div"inputDiv"的子节点的文本输入字段的宽度为125px,除了某些特定输入获得一些其他宽度.问题是第一个声明会覆盖特定的项声明.

我尝试过以下方法:

  1. 追加!对每个特定宽度都很重要.工作,但许多声称(正确地,我认为)!重要应该避免,并且它是相当麻烦的,因为它必须添加到具有特定宽度的每个元素.
  2. 将#inputDiv添加到每个特定选择器,即#inputDiv#differentInput1再次,工作,并避免使用!important的问题,但仍然很麻烦,因为必须对每个元素进行操作.

有没有办法简单地说第一个声明中的项目不太重要,不应该覆盖任何东西?

Exp*_*lls 15

没有办法做到这一点,因为它与CSS的对立方式!important是相同的- 相反的做法就像滥用一样.您唯一的选择是依赖选择器特异性.inputDiv例如,通过使用类而不是ID,您可以以不那么麻烦的方式编写它.

  • 显然是错误的断言。级联是一个重要的机制,但不是 css 的目标。在 Scss 中你有 !default 修饰符,所以任何东西都可以覆盖它。如果它存在于 CSS 库中,则可以提供一种从未推翻您定义的默认样式。 (2认同)

car*_*mba 5

也许是一种解决您的问题或回答您的问题的方法,您可以尝试这样的方法

( 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/ )