I am having trouble applying a style that is !important
. I’ve tried:
$("#elem").css("width", "100px !important");
This does nothing; no width style whatsoever is applied. Is there a jQuery-ish way of applying such a style without having to overwrite cssText
(which would mean I’d need to parse it first, etc.)?
Edit: I should add that I have a stylesheet with an !important
style that I am trying to override with an !important
style inline, so using .width()
and the like does not work since it gets overridden by my external !important
style.
Also, the value that will override the previous value is computed, so I cannot simply create another external style.
The ! important rule in CSS is used to add more importance to a property/value than normal. In fact, if you use the ! important rule, it will override ALL previous styling rules for that specific property on that element!
In CSS, important means that only the ! important property value is to be applied to an element and all other declarations on the element are to be ignored. In other words, an important rule can be used to override other styling rules in CSS.
You cannot override inline CSS if it has ! important . It has higher precedence than the style in your external CSS file. However, if you want it to change some actions later on, you can use a bit of JavaScript.
important is a bad CSS practice. It disrupts the natural flow in applying the css rules where in properties are applied from top to bottom. With ! important , the property will now give priority to the latest important value.
The problem is caused by jQuery not understanding the !important
attribute, and as such fails to apply the rule.
You might be able to work around that problem, and apply the rule by referring to it, via addClass()
:
.importantRule { width: 100px !important; } $('#elem').addClass('importantRule');
Or by using attr()
:
$('#elem').attr('style', 'width: 100px !important');
The latter approach would unset any previously set in-line style rules, though. So use with care.
Of course, there's a good argument that @Nick Craver's method is easier/wiser.
The above, attr()
approach modified slightly to preserve the original style
string/properties, and modified as suggested by falko in a comment:
$('#elem').attr('style', function(i,s) { return (s || '') + 'width: 100px !important;' });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With