Style Precedence

Question: I'm having trouble with changing the colour of links on pages controlled by style sheets. Is there a good reference for the order that styles are applied? If I put a style="color:green;" on an anchor tag, for example, the color from the main external style sheet still overrides it. What has precedence, and how can you cancel that precedence?

Answer: The order of precedence is as follows:

  1. User styles take precedence over author styles (that's how browsers treat it but the specification says the other way around)
  2. class or id styles take precedence over general styles.
  3. More specific styles take precedence over less specific styles.
  4. Styles marked !important take precedence over styles not so marked.
  5. The closest defined style that applies takes precedence over those defined earlier in the page.

The one tag where it is very difficult to assign the style to the tag itself is the anchor tag because you need separate definitions for a:link, a:active, a:hover, and a:visited. The easiest way to set up a colour definition for an anchor tag is to define a class eg:

<style>,,, {color:green;}
<a class="green" ... >

The reason why applying styles directly to the <a> tag doesn't work is because all of the :link :visited :hover :focus and :active alternatives (which can only be specified in a style sheet and not within a style attribute) are all more specific than the style that is applied to the tag itself and so the more specific reference in the style sheet takes precedence over the closer but less specific reference on the tag itself.

Your live web pages ought to have all of the styles defined either between style tags at the top of the page or even better in an external style sheet. You should only be attaching styles to tags directly using the style attribute while you are testing your page and should replace all those with ids or classes prior to uploading your page to the web.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow