Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS !important doesn't seem to work in jQuery/Firefox 3.x

See fiddle: http://jsfiddle.net/csaltyj/P2sLa/

In Chrome, this works fine, but in Firefox it does not, and yields a Javascript warning. I know the !important isn't required here, but I have a large-scale project where it is required, and it's causing Firefox to break. Any ideas?

like image 650
CaptSaltyJack Avatar asked May 02 '11 18:05

CaptSaltyJack


People also ask

How can we make CSS property important in jQuery?

You can do this: $("#elem"). css("cssText", "width: 100px ! important;");

Can we add important in jQuery?

important is used to increase the priority of a CSS property. This ignores the overriding properties. In jQuery, you can use the css() method to manipulate style property of the selector but this doesn't allow to set ! important to property.

How do you add an important attribute in css?

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!


1 Answers

Searching for "jquery css important" brought up a blog post explaining the "problem".
I'll post some additional information, but to make a long story short, here's your solution:

$('#set-bg').click(function() {
    $('#box').css('cssText', 'background: blue !important');
});

The author states that:

This is not a bug but something that most browser doesn’t acknowledge a need since inline style already have the highest priority other than user defined ones. (unless you do not want your user to change how they view your website).

Please note that using cssText has one disadvantage and you might want to consider
using cssRules instead:

cssText will overwrites the css of that particular element. Hence, you will have to redeclare the rule for that particular element all over again.

With all that said. Please listen to the author's summary:

Using !important in CSS is not advisable since it might kill your web usability. Furthermore, there is no reason why !important should be use as inline styling already has the highest priority. Hence, you might want to reconsider applying !important on your script after thinking about the consequences that might bought to your users.

like image 79
rubiii Avatar answered Oct 09 '22 16:10

rubiii