Family relationships: descendants, children, and siblings
CSS enables the application of rules based not only on an element's name, but also on its position within the overall document. For example, a rule might select links, but only if they are within a paragraph tag. In the Document Object Model, this is known as being a descendant of the paragraph element, which is the ancestor. In this case, the selector is the ancestor element name followed by the descendant element name. For example, the following code in Listing 7 removes the underline for any links that are part of a paragraph (as opposed to those within the table) as shown in Figure 6.
Listing 7. Using the ID selector
|
Note that this rule applies to a link anywhere within a paragraph, even if it's nested within another element. For example, if the HTML were actually:
<p><b><a href="complete">Complete results</a></b></p>
the link would still be a descendant of the paragraph element.
It is possible, however, to limit the selector to only the direct (first generation, so to speak) child of the ancestor, or parent. The child selector, which at the time of this writing is only supported by Netscape 6 and above, restricts a rule to immediate children of the parent element. The child selector uses the greater-than sign, like this:
p > a { text-decoration: none }
Another newer selector that hasn't made its way to Internet Explorer yet is the
following sibling selector, which uses a plus sign (+
). In
this case, a rule applies only to elements that immediately follow another particular
element. For example, the following code in Listing 8 italicizes only an h4
element that follows another h4
element, so the first
h4
element remains unchanged, as shown in Figure 6.
|
Figure 6. Descendant, child, and following-sibling selectors
View Use Cascading Style Sheets Selectors Discussion
Page: 1 2 3 4 5 6 Next Page: Pseudo-classes and Pseudo-elements