Simple Contextual Selectors


A contextual selector is a selector that takes into account the context in which the style is to be applied. That is, the specified style is applied to an element only if the element is in the specified context. An element's context is formed by its ancestor elements and the elements that precede it. In this section, we look only at the ancestors. The section, "Advanced contextual selectors," describes how other contexts can be added to a selector.

Suppose you were to write these two rules:

 H1 { color: red } EM { color: red } 

These rules will work fine. H1 headings will turn red, and so will EM elements. Now, suppose you have this code in your document:

 <H1>This headline is <EM>very</EM> important.</H1> 

You want to emphasize "very" but because both the EM and the H1 are set to red, you will lose the emphasis provided by EM. You want both EM and H1 to stay red for the document as a whole, but for EM elements inside H1, you need to come up with some other way to emphasize "very." You still want to use the EM element. How do you do it?

Using a contextual selector, you can specify a rule that applies only to EMS that are inside H1 elements. No other EM elements are affected. Consider this rule:

 H1 EM { color: blue } 

In English, this rule says: "For any EM that is inside H1, make it blue (and not red like the previous rule specified)." Thus, the EM will be made blue only in the context of an H1. In all other contexts, it will be red as usual. Hence, the name contextual selector.

Contextual selectors are made up of two or more simple selectors separated by white space. Any type, class, or ID selector is a simple selector. Also, combinations of type and class selectors, as described in the previous section, are regarded as simple selectors.



Cascading Style Sheets(c) Designing for the Web
Cascading Style Sheets: Designing for the Web (3rd Edition)
ISBN: 0321193121
EAN: 2147483647
Year: 2003
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net