[section_title title=Part Three – The CSS Order of Precedence]

Part Three: The CSS Order of Precedence

Sometimes, CSS can be frustrating when you make a rule in your CSS document and the change is not what you expect when you see the linked web page in a browser. By understanding a little bit about the CSS Order of Precedence, you will have fewer moments of frustration.

Helpful Hint #1: If you’re placing two rules on one element, using the same class selector, and both rules are in the same style sheet, the rule that is further down will override the rule that is higher up in the style sheet.

For example:

.favorite {color: red;}
.favorite {color: black;}

The color will be black.

You may think that you will never do this when you write your CSS rules, but the day may come when you go back to a style sheet that you started a year earlier. You add a new rule, hoping to change something in your web page to RED, but then nothing happens. You go back and look at your rule. It is coded perfectly. You look at your web page in the browser again. You refresh your web browser 3 times. Still… nothing changes. Finally, you examine your style sheet, rule by rule. You discover the same rule listed twice (with different values in the declaration).

Helpful Hint #2:  It’s also useful to note that if a link to an external style sheets is placed underneath a link to another style sheet, the styles in the lowest style sheet override those in the higher style sheet.

<link rel=”stylesheet” href=”style.css”>
<link rel=”stylesheet” href=”layout.css”>

We discussed how to link to external style sheets in our related tutorial: Smooth Strides from HTML to HTML5.

CSS Order of PrecedenceHelpful Hint #3: Different selectors naturally override others.

Here is the order in which this takes place:

  1. The ID selector
  2. The attribute selector
  3. The class selector
  4. The child selector
  5. The adjacent sibling selector
  6. The descendant selector
  7. The type selector

The ID selector overrides all the other selectors. It is the most important. So if your web page is not doing what you think it should, consider the selectors you are using, the order in which you are using them in and the style sheet where they are placed.

Using IDs and Classes

In our related tutorial, we mentioned a tag <div id=”wrapper”>.

We can style that tag by using this code in our CSS style sheet:

#wrapper {text-align: center;}

The (#) sign refers to an ID tag. It is specific. There can only be one ID of #wrapper in a web page.

We also mentioned a tag <span class=”special”>. We can style that tag by using this code in our CSS style sheet.

. special {color: red;}

The (.) sign refers to a CLASS tag. It is not that specific and can be overridden with an ID selector. You can write <span class=”special”> in your web page as many times as you like.

Learn more about ID and Class Selectors.