0

I'm trying to apply a style to an element and define his importancy, as the following code:

$('div').css('height','50px !important');

But it does not work, what is the correct way?

Marvin Medeiros
  • 202
  • 4
  • 22
  • It's considered best practice to avoid the use of `!important` completely by structuring your CSS rules so that the specificity of the rule is enough to ensure it's applied where required. That said, the duplicate answer I marked has a workable solution for the specific issue. – Rory McCrossan Apr 13 '16 at 12:53
  • I'm actually looking for a solution that not unnecessarily extend jQuery for it – Marvin Medeiros Apr 13 '16 at 13:16

2 Answers2

1

You shouldn't ever need to add important to an elements style via jQuery unless you're already using !important somewhere else. When jQuery adds styling to an element, it adds it in the style attribute which will overwrite all previous styling, unless it's being given !important.

You should try and stay away from using !important and try to write your styling out so that it has specificity.

If you really need to add that styling to overwrite others, your best bet is to add a class that has !important on it.

$('div').addClass('important-height');
silverlight513
  • 5,268
  • 4
  • 26
  • 38
1

If you must do this with JQuery (not recommended). You need to modify the style attribute like so;

$('div').attr('height', '50px !important');

The .css function will not add !important properties.

Novocaine
  • 4,692
  • 4
  • 44
  • 66