How to Override Inline Styles from an External Stylesheet

All web developers know that by default, inline styles take precedence over styles in external stylesheets. For example, the following inline style declaration:

<span style="color: red;">Red text</span>Code language: HTML, XML (xml)

will ensure the “Red text” is coloured red, even if the following is included in an external CSS file, or in the <head> styles:

span { color: blue; }Code language: CSS (css)

Now it is generally not a good idea to use inline styles, as one should avoid mixing markup (responsible for the content and structure) with styles (responsible for the presentation format). Sometimes this is out of our control, for example if you are using a CMS which generates HTML with inline styles. In this case, how do you override these inline styles to ensure the page looks right?

Fortunately, this is easily done by using the following CSS magic:

span[style] { color: blue; }Code language: CSS (css)

The presence of the magic [style] attribute ensures that this style declaration overrides whatever inline styles are specified for the <span> elements.

I know this trick is generally well known, but it’s useful enough to restate it, just in case you’ve somehow not discovered it yet! In addition, please note that as with most useful CSS techniques, I believe this is not supported in Internet Explorer 6 or 7.

A slight aside – you can also use the “!important” CSS rule to assign greater priority to specific styles, regardless of where they are declared, but this approach is frowned upon as it can interfere with style customisations made for accessibility reasons, and can also be a sign of poorly defined or structured CSS.

Leave a Reply