How to add !important when you are using css method in jQuery

Post Pic

Most of the developers might have faced this situation where they need to add !important while using css method in jQuery. Mostly we need to avoid using !important in our CSS style sheets but in some situations we are forced to use the same. For example: when we want to change the font-size of sub elements under a parent element because of some inheritance the font-size might not change, in these scenarios – most of the developers forcefully apply !important as a simple work-around.

If you want to add !important dynamically while using css method, then here is the way to do so.

1
$("#addImportant").css("cssText","font-size:15 !important;");

When we add the above line into your page, it will render like below, assuming that it has been applied to a div of id named ‘addImportant':

1
<div id="addImportant" style="font-size:15px !important"></div>

The above snippet has helped me in resolving one of the task which I need to complete, and hope this might help you some situation.

Related Entries...

Advertisement

Please let us know your feedback about the article through the comments section below, we want to hear from you about our website. And your comment / advice may help us to serve you better in upcoming articles.

Thank You!
Vivekanand [Founder of DeveloperSnippets]

5 Responses

01.12.10

Why would you need to add !important to an inline style. If you need !important rules on an inline style, your CSS is already probably pretty wacky.

[…] This post was mentioned on Twitter by bkmacdaddy designs, WPstudios. WPstudios said: RT @bkmacdaddy How to add !important when you are using #CSS method in #jQuery http://bit.ly/8ioWx9 […]

Social comments and analytics for this post…

This post was mentioned on Twitter by allwebdesign: How to add !important when you are using css method in jQuery: Most of the developers might have faced this situat… http://bit.ly/6mlW4C

[…] This post was mentioned on Twitter by Mike Lane, Mike Lane, Propeople, anthony cousins, jQuery Tips and others. jQuery Tips said: How to add !important when you are using CSS method in jQuery http://bit.ly/5bkL4j […]

01.12.10

I found this post very helpful thanks – I couldn’t find the information I needed anywhere until here.

Contrary to the first comment, I needed this because I was altering a WordPress theme, and a carousel was loading wrongly – it was supposed to load with visibility:hidden and then a javascript changed the style to visible when the pictures were loaded. Instead the pictures were appearing in the wrong place and wrong style and looking ugly, and I couldn’t figure out why.

In the end, I made the CSS style “visibility:hidden !important”, which stopped the ugly loading from appearing, but then I needed to over-ride this in the javascript, and that required an inline !important. It worked.

So thanks.

Leave Your Response

* Name, Email, Comment are Required