1

I have a Greasemonkey script that applies styles with either .css() or GM_addStyle(). These styles are getting overwritten by the styles that are on the page, causing undesired effects.

I know that I can fix this by using !important on all of my styles, but I really don't want to do this. Is there any way to do this w/o using !important?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Steve
  • 93
  • 2
  • 9
  • `.css()` should override everything except `!important` rules. That means, you will probably have to fight `!important` with `!important`. – Fabrício Matté Feb 25 '13 at 23:15
  • 1
    can you show me a html/css snippet from the console? – Francis Kim Feb 25 '13 at 23:20
  • 1
    so you want the Greasemonkey `GM_addStyle()` or `.css()` to have precedence over page CSS right? – Francis Kim Feb 25 '13 at 23:25
  • Yes, as far as i can tell there aren't any other !important rules on the page i'm trying it on – Steve Feb 25 '13 at 23:40
  • Duplicate of [Overriding !important style using Javascript](http://stackoverflow.com/questions/462537/overriding-important-style-using-javascript) and of [Element's CSS, reverts back at the end of page load?](http://stackoverflow.com/q/14618541/331508). – Brock Adams Feb 26 '13 at 00:30

1 Answers1

0

There is nothing wrong with using !important in Greasemonkey scripts and Stylish styles. (It is sometimes misused in regular web pages, but userscripts are different).

!important is the only way to override styles set in attributes. For example, if we want to change this:

<div id="annoyingBlock" style="background: red; top: 4em; display: inline block ... Bunch of other styles that we don't want to touch.">
    Look at me!
</div>

to have a white background, our userscript must either overwrite that style attribute (which can be a right pain on large complex sites and can bust the other inline styles we may still want) or, it must use the !important flag, like so:

GM_addStyle ( "                                 \
    #annoyingBlock {                            \
        background:         white !important;   \
    }                                           \
" );


This is because attributes (inline styles) have a higher precedence over anything but !important styles.



If your style changes using .css() are getting overwritten by the page's javascript, use a technique like in this answer to combat that.

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295