Monday, October 4, 2010

Css Tutorial : Contextual Selectors

Now there’s a horribly scary term. In the previous section, a heading containing emphasized
text was used to illustrate basic inheritance. Remember that the em selector was added to ensure the
<em> element in the (X)HTML would be rendered with red text. Here’s the CSS again:
/* Top-level heading */
h1 {
color:#333;
}
/* Make emphasized text shine brightly */
em {
color:#F00;
}
The downside of this is that all emphasized text across the whole web site would also
become red, regardless of its parent element. Assuming the rule is only meant to target the <em>
element when a child of <h1> headings, a simple adjustment can be made to put the emphasized
text into context:
/* Make emphasized text shine brightly ONLY when it’s the child of an h1 heading */
h1 em {
color:#F00;
}
Contextual selectors consist of two or more simple selectors separated by whitespace.
Here the contextual selector is constructed to show that the rule will only have an effect when
the last selector (em) is a direct descendent (be it a child, grandchild, great grandchild, or so on)
of the first selector (h1). If the browser does not find an exact match (i.e., it only finds <em> elements
outside of <h1> elements), it will not apply the styles dictated by the contextual selector to them.
Here’s similar markup to the original example, but with a paragraph acting as the parent
to a second <em> element:

<h1>This is the greatest heading <em>in the world</em></h1>
<p>I'm sorry but it simply is <em>not</em>, you fool.</p>
The <em> element owned by the <h1> element will be red, whereas the one owned by the
paragraph will not—it will inherit the default font color. To control the style of any emphasized
text that is out of context, simply define a new selector for em with the values you desire, or
maybe create a new contextual selector with p as the parent to your em.
In Chapter 6, contextual selectors will be used to gain tight control of nested elements
such as hierarchical lists and other problematic situations.

No comments:

Post a Comment