Cascading Styles

And finally, we need to consider how rules from different locations cascade to determin exactly what style definition should be used when more than one rule applies.

With so many different places where style definitions can be given, we need a clear and precise method of chosing which rules should be applied.

The general idea is fairly intuitive - all the rules that apply should be used and where there are conflicts, the values from the most local rule should be used. So, for example, consider the situation where we have a class rule for a class called myStyle, but there is a rule in an external style sheet and also a rule for the same class defined internal to the page:

SourceRule
External
.myStyle {
    font-family: Georgia, "Times New Roman", Times, serif;
    color: #00F;
}
Internal
.myStyle {
    font-size: 110%;
    color: #900;
}
   

The effect of these two rules combined can be seen in this brief paragraph (assuming that the internally defined rule appears after the directive to load the external style sheet).

The external rule defines a font family (Georgia) and a colour (blue). The internal rule defines a size (110%) and a colour (dark red). The font from the external rules and the size from the internal rule apply without problem, but the colour in the external rule is contradicted by the colour in the internal rule. Because the internal rule is more specific, its colour specification is used.

This paragraph also has the class myStyle applied, so it gets the properties from the two rules as discussed above. However...

It also has an inline style applied, which specifies a colour code of #0A0 (dark green). Because the inline style is more specific than either of the other rules, this is the colour that actually gets applied to the paragraph.

This is the basic idea behind cascading styles. There are a couple of additional complexities involving whether a rule has been declared as important, and the rules used to calculate which styles are more specific based on their selectors. If you want to know more details about this, then the following sites have some useful information:

The last page in this series gives links to some additional reading... Next