XML technologies / CSS / Advanced websites with CSS / Text effects and cascading / Cascading and inheritance in CSS / Order of events

(Excerpt from “CSS − Advanced websites with Cascading Stylesheets” by Rachel Andrew & Dan Shafer)

There are three ways to assign style rules: an external stylesheet, an embedded stylesheet or the attribute style in the HTML tag. The order of events does not depend on where a rule is defined, only on where it takes effect.

Consider an example. The external stylesheet mylayout.css contains the following rule:

h2 {
  color: green;
}

On a particular page, however, h2 should differ from its “normal” appearance and use another color. For example, define another color in an embedded stylesheet for h2.

h2 {
  color: blue;
}

This embedded stylesheet takes effect only if you insert it into the page header with a tag <style> after the external stylesheet’s tag <link>. The order-of-events principle then gives it precedence over the other stylesheet.

With just one property definition, as in our example, the order-of-events principle is easy to follow. The embedded rule overrides the external stylesheet: all elements h2 appear blue on the page. Note that the second rule does not actually overwrite the first; it simply dominates because it was declared later. Move the tag <style> before the tag <link>, and all elements h2 appear green again.

Unfortunately, things are not always so clear-cut. We will extend the green-heading example by adding some more properties to the external stylesheet.

h2 {
  color: green;
  background-color: transparent;
  margin-left: 10px;
  font-family: Arial, Helvetica, sans-serif;
  text-decoration: overline;
}

On another page, we use the following rule in an embedded stylesheet:

h2 {
  margin-left: 20px;
  text-decoration: none;
}

Again, we insert the embedded rules after the link to the external CSS file. Properties from the external stylesheet also apply if the embedded stylesheet, which again takes precedence, does not define them differently. The heading h2 therefore appears green with a transparent background and the external stylesheet’s fonts, together with the embedded stylesheet’s 20-pixel left padding and disabled text decoration.

Think of this process as a waterfall. It starts with certain declarations (in our example, for color, background-color, margin-left, font-family and text-decoration). These formatting rules then flow like water over rocks. When a rock has an already defined rule with different values, cascading takes effect and the new values are adopted.

When two or more style rules compete for an element, the rule declared last takes precedence. This assumes, of course, that the more important criteria—specificity, origin and weight—are equal.

  

 

 

 

back to top