can an entire css ".class" have it's specificity as !important?

MacLovin picture MacLovin · May 11, 2013 · Viewed 33.3k times · Source

I am working heavily in jQuery UI widgets and themeing is becoming hard because of an oversight that I need to work around.

Consider this problem:

<div id="node" class="ui-widget">
    <div class="ui-widget-content">
    </div>
</div>

then this jquery

<script>
 $(function() { 
       $('#node').hover(function (){
           $(this).toggleClass("ui-state-error");
       });
 }); 
</script>

I would like the ui-state-error to be !important to the nested div. This is pseudo code, but I find large examples of this happening where containers have css swaps and children (basicaly) ignore it. What is even worse is this: if I would like to be able to overwrite in jQuery say "backgroundcolor=ui-state-error:background-color knowing 100% it all won't go to pieces because I don't "know" necessarily that that background is the important one for the element in question.

here is a fiddle of a case in point http://jsfiddle.net/WCuYH/1/

EDIT I am going to recommend this question is closed because there hasn't been any attempts at answers, only too much drift from the essence of the original post

Answer

jfriend00 picture jfriend00 · May 11, 2013

First off !important applies to one specific declaration in a CSS rule. It doesn't apply to a class. So, "no" you can't make a class !important.

Second off, !important is just one part of CSS specificity. You can also use other ways to make a rule be a more specific rule to have precedence (such as referring to an id in the parent chain instead of just the class. When I'm writing CSS, using !important is my last possible choice - I'd much rather solve overrides with other specificity solutions. Usually, if you control all the CSS, this is pretty easy to avoid using !important. If you have to override some CSS that you don't control, then sometimes it is handy.

If your jQuery code is going to toggle a class on the object, then you will have to craft your CSS rules so that adding/removing this class causes the right CSS declarations to have precedence. For us to help you further with that part, you would need to show us the relevant parts of both your HTML and CSS so we could advise on how to solve your precedence/specificity problem.