I'm building a jQuery plugin that uses CSS styles to add colors and margins to nested DIV tags. Since I'd rather keep the plugin as a single file, my code adds these colors and margins directly as CSS attributes to the DIVs using jQuery's .css()
method. (The values for these attributes can be customized when the plugin is initialized.)
However, I also wanted to give users the power to style these DIVs using their own stylesheets, so I'm also adding classes to each group of DIVs (for which the names can also be customized). This seemed like the best way to provide the best of both worlds.
The only drawback seems to be that inline style="..."
attributes (generated by jQuery's .css()
method) always override class styles set in the external stylesheet. I can, of course, use !important
styles in the stylesheet, but doing this again and again is cumbersome.
So: what I really want is a way to make the inline styles automatically take a lower priority than the external class styles, without having to make the external class styles !important
.
I have not read about such a thing. Any suggestions? (Or: is there another approach I should be taking to style my DIVs in the plugin?)
What's the opposite of
!important
in CSS?
There isn't an exact opposite, but there are lower precedence selectors.
w3c spec defines the cascade, might as well read it.
inline styles have highest precedence, and you're after a low-precedence style, you'll need to add CSS via a stylesheet or style
element.
Because you're using jQuery, adding a custom style element is very easy:
$('<style type="text/css">.foo {color: #FF0000;}</style>').prependTo('head');
The issue you're then going to find is that a user who has specified .foo
in a stylesheet will need a higher specificity to win out over the style
element, so I'd recommend using an additional class for each element so that a user can override the defaults:
.foo.override { color: #0000FF; }
In all cases you're going to want to carefully pick your selectors to have the least specificity possible.
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