Monday, October 4, 2010

Careful with the Cascade

It can sometimes be hard to track the cascade across several style sheets. For example, if two
selectors have matching properties but varying values, e.g., each instance of a selector was made up
of font-family, color, and background, but with different values for each, the selector in the
style sheet with the highest hierarchy would win out and be rendered. Things get even more
interesting when each selector has unique properties.
Let’s clarify this with an example. Imagine that in a modular style sheet such as forms.css
you have defined a class called highlight as follows:
/* Highlight important form information */
.highlight {
color:#F00;
font-style:italic;
text-decoration:underline;
}
Should there be no other instance of that selector in any style sheets higher up the hierarchy,
highlight will indeed be rendered in red italicized text with a neat underline. However,
imagine that a few weeks later in external.css, a style sheet of more hierarchical importance,
you’ve forgotten about the original class and decide to reuse highlight as follows:
/* Highlight author’s name underneath articles */
.highlight {
color:#F00;
font-style:normal;
}
First, the cascade dictates that the font-style value for highlight in external.css (fontstyle:
normal;) is of greater importance than the value in forms.css (font-style: italic;).
Therefore, all instances of highlight sitewide will be normal red text, not italicized. Without
realizing it, you have just turned all your lovely italicized form text into boring normal text, and
you probably won’t notice until you revisit your forms in your browser.
And to further illustrate this pitfall, the new highlight class in external.css does not define a
value for text-decoration, so the normal red text you wished to create will be underlined, taking
that value from forms.css. Sure, your new highlight class takes precedence in the hierarchy,
but unless you turn off the underline in external.css, the cascade will still find its way to the
original rule and look for anything not being overruled.

No comments:

Post a Comment