By Andy Harris

With inherited CSS3 styles comes the ability to override an inherited style rule. For example, take a look at the following code to get an idea of what this could mean:

<!DOCTYPE html>
<html lang = "en-US">
 <head>
 <meta charset = "UTF-8">
 <title>overRide.html</title>
 <style type = "text/css">
  body { color: red; }
  p {color: green; }
  .myClass { color: blue; }
  #whatColor { color: purple; }
 </style>
 </head>
 <body>
 <div>
  This div has only the style from the body.
 </div>
 <p>
  This is a regular paragraph with paragraph styling
 </p>
 <p class = "myClass">
  This paragraph is a member of a class
 </p>
 <p class = "myClass" id = "whatColor">
  This paragraph is a member of a class and has an ID,
  both with style rules.
 </p>
 </body>
</html>

The question is this: What color will the whatColor element display? It’s a member of the body, so it should be red. It’s also a paragraph, and paragraphs are green. It’s also a member of the myClass class, so it should be blue. Finally, it’s named whatColor, and elements with this ID should be purple.

Four seemingly conflicting color rules are all dropped on this poor element. What color will it be?

CSS has a clear ranking system for handling this type of situation. In general, more specific rules trump more general rules. Here’s the precedence (from highest to lowest precedence):

  1. User preference

    The user always has the final choice about what styles are used. Users aren’t required to use any styles at all and can always change the style sheet for their own local copy of the page. If a user needs to apply a special style (for example, high contrast for people with visual disabilities), he should always have that option.

  2. Local style

    A local style (defined with the style attribute in the HTML) has the highest precedence of developer-defined styles. It overrules any other styles.

  3. id

    A style attached to an element id has a great deal of weight because it overrides any other styles defined in the style sheet.

  4. Class

    Styles attached to a class override the style of the object’s element. So, if you have a paragraph with a color green that belongs to a class colored blue, the element will be blue because class styles outrank element styles.

  5. Element

    The element style takes precedence over any of its containers. For example, if a paragraph is inside a div, the paragraph style has the potential to override both the div and the body.

  6. Container element

    divs, tables, lists, and other elements used as containers pass their styles on. If an element is inside one or more of these containers, it can inherit style attributes from them.

  7. Body

    Anything defined in the body style is an overall page default, but it will be overridden by any other styles.

In the overRide.html example, the id rule takes precedence, so the paragraph displays in purple.