Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I have to use ! important in this case?

Tags:

css

less

I'm learning CSS and I have the result I want but only if I use the ! important; specification. I don't understand why I can't override a property inheriting one class and overriding a property.

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;

}

I thought that if I use the above style for a button:

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

then I wouldn't have to use the ! important; statement and the override would work without it, but it doesn't. What am I missing? can you please help me understand why it doesn't work without the ! important statement, or show me a way do to it without ! important; ?

like image 907
Niklas Rosencrantz Avatar asked Dec 10 '22 22:12

Niklas Rosencrantz


2 Answers

Its is not entirely correct that it isnt overridden because its set in the class above, in this instance it isnt due to the order of your LESS - it isnt being overridden because you have listed your classes in the wrong order- instead of

extra-questions minor-action

You need to do

minor-action extra-questions

When denoting classes, if they share values for the same property settings- those values for the last class applied will take precedence.

Alternatively, you can add more specificity to your classes, in your LESS, nest extra-questions within minor-action and prefix with &. This will mean the order of classes in your HTML does not matter, the combination does. The output CSS will be:

.minor-action.extra-questions

Also, as I am sure you are aware, using !important should be avoided

like image 117
SW4 Avatar answered Jan 01 '23 04:01

SW4


Your example works without !important - http://jsfiddle.net/sgguap7v/

It does not work !important without that case - 1. The rule is to follow the class - .extra-questions {} .minor-action {} 2. The rule has a higher weight - button.minor-action {} It has a greater weight than .minor-action {}

like image 26
Tom910 Avatar answered Jan 01 '23 05:01

Tom910