Thursday, June 23, 2011

How to Override Inline Styles with Style Sheet

Often we think of inline styles as a way to override styles we set up in the CSS. 99% of the time, this is the case, and it's very handy. But there are some circumstances where you need to do it the other way around. As in, there are inline styles on some markup that you absolutely can't remove, but you need to override what those styles are. This could be markup that is being inserted onto the page from foreign JavaScript or perhaps generated from the bowels of a CMS that you cannot control easily.


Thank our lucky stars, we CAN override inline styles directly from the stylesheet. Take this example markup:


Eg 1:

<div style="background: red;">
    The inline styles for this div should make it red.</div>

div[style] {
   background: yellow !important;
}

Eg 2:
<div class="block">
 <span style="font-weight: bold; color: red;">Hello World</span>
</div>

.block span[style]{
    font-weight: normal !important;
    color: #000 !important;
}

Unfortunately the down side of this is technique is that it will not
work on IE6 and below, but it does work in IE7, IE8, Fire Fox, Safari,
and Opera.

1 comment: