为什么我要用!在这种情况下重要吗?

Nik*_*ntz 3 css less

我正在学习CSS,我有我想要的结果,但前提是我使用的是! important;规范.我不明白为什么我不能覆盖继承一个类并重写属性的属性.

form button.minor-action,
#profile-left a.action,
.minor-action {
  display: inline-block;
  background: @lightBlue;
  color: white;
  padding: 0 1.2em;
  border-radius: 4px;
  -webkit-border-radius: 4px;
  -moz-border-radius: 4px;
  -ms-border-radius: 4px;
  text-decoration: none;
  text-align: center;
  font-weight: bold;
  border: none;
  height: 25px;
  margin-top:1.0em;
  line-height:25px;
  white-space: nowrap;
  &:visited {
    color: white;
  }
  &:hover, &:active, &:focus {
    background-color: darken(@lightBlue, 10%);
    text-decoration: none;
  }

  &.call-to-action {
    background-color: @pink;
    &:hover, &:active, &:focus {
      background-color: darken(@pink, 10%);
      text-decoration: none;
    }
  }
}

.extra-questions {
  margin-top: 0em !important;

}
Run Code Online (Sandbox Code Playgroud)

我想如果我将上面的样式用于按钮:

<button id="add_question" class="extra-questions minor-action">{% trans "Lägg till ny" %}</button>

然后我不必使用该! important;语句,并且覆盖将在没有它的情况下工作,但事实并非如此.我错过了什么?你可以帮助我理解为什么没有这个! important声明它不起作用,或者告诉我一个没有办法的方法! important;吗?

SW4*_*SW4 5

它不是完全正确的,因为它没有被覆盖,因为它在上面的类中设置,在这种情况下它不是由于你的LESS的顺序 - 它没有被覆盖,因为你已经以错误的顺序列出你的类 - 而不是

extra-questions minor-action

你需要这样做

minor-action extra-questions

表示类时,如果它们共享相同属性设置的值,则应用的最后一个类的值将优先.

或者,你可以添加更多的特异性你的类,在你的LESS,窝extra-questionsminor-action,并用前缀&.这意味着HTML中的类顺序无关紧要,组合确实如此.输出CSS将是:

.minor-action.extra-questions

此外,我相信你知道,!important应该避免使用

  • 对不起,如果你在给定链接上进一步阅读,他们会指出它... (2认同)