Thwarting Descendant Selectors ..............................................................
Warning: At this time, you cannot apply this next selector trick to code used
in Internet Explorer — it won’t work. What if you only want a child element to
be selected, not an entire series of descendants? To do that, you use the >
symbol, which means only if it’s a child. Here’s how that looks:
p > i {color: blue;}
This means, “Color blue any italic that is a child of a paragraph. But don’t go
any further if the italic has any children or descendants.” So, in the following
paragraph, the strong element won’t inherit the blue color:
<P>
Here’s a paragraph with <i>italics, but <strong>also some
strong child inside</strong>the italics</i>.
In some cases, you don’t want to select an arbitrarily descended element;
rather, you want to narrow your range to select an element that is a child of
another element. You might, for example, want to select a strongelement
only if it is a child (as opposed to a descendant) of an H1 element. To do this,
you use the child combinator, which is the greater-than symbol (>):
h1 > strong {color: red;}
This rule makes the strongelement shown in the first H1 below red but not
in the second:
<h1>This is <strong>very</strong> important.</h1>
<h1>This is <em>really <strong>very</strong></em>
important.</h1>
Read right to left, the selector h1 > strongtranslates as “selects any strong
element that is a child of an H1 element.” The childcombinator is optionally
surrounded by white space. Thus, h1 > strong,h1> strong, and h1>strong
are all equivalent. You can use or omit white space as you like.
You can also specify a selector in a way that works on adjacent siblings
(like two paragraphs that share the same <body>element as their parent).
You specify them using the + sign. This, too, however, has not been adopted
by Microsoft’s Internet Explorer.
Chapter 14: Specializing in Selection 263