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?

2
  • 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. Commented Apr 13, 2016 at 12:53
  • I'm actually looking for a solution that not unnecessarily extend jQuery for it Commented Apr 13, 2016 at 13:16

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.