|
| ||||
| ||||
|
|
Contextual selectors are a slightly trickier form of selectors. A
contextual selector selects an element with a certain kind of
ancestor. An ancestor element is an element that contains the
element we want to select. The ancestor is not necessarily the direct
parent of the element in question. This is best illustrated by example.
In the following HTML document, in the second paragraph, the
DIV element is an ancestor of the STRONG
element. The STRONG element's parent element is the
P element, that is, the element in which it is contained.
Since the DIV element is the parent of the P
element, it is also an ancestor of the P element.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"
"http://www.w3.org/TR/REC-html40/strict.dtd">
<HTML>
<TITLE>Example HTML Document Showcasing
CSS Contextual Selectors</TITLE>
<STYLE TYPE="text/css">
<!--
BODY {
color: blue;
background-color: cyan;
font-family: Helvetica, Arial, sans-serif;
}
H1, H2 {
color: red;
font-family: Garamond, Times, sans-serif;
}
EM { font-style: normal; color: red; }
H1 EM { color: green; }
DIV.special STRONG { color: purple;
font-weight: normal; }
-->
</STYLE>
<BODY>
<H1>Heading 1 with <EM>Emphasis</EM></H1>
<P>A paragraph. A paragraph. A paragraph.
A paragraph. A paragraph. A paragraph. A paragraph.
A paragraph. <EM>Some emphasis</EM>.
A paragraph. A paragraph. A paragraph. A paragraph.
A paragraph.
<DIV CLASS="special">
<P>A paragraph. A paragraph. A paragraph.
A paragraph. A paragraph. A paragraph. A paragraph. A
paragraph. A paragraph. A paragraph. A paragraph.
A paragraph. A paragraph. <STRONG>Some
Strong Emphasis</STRONG>. A paragraph.
A paragraph. A paragraph.</DIV>
This example also illustrates the primary use of contextual
selectors. In this example, I have chosen to make all level 1 headings
red, and also make EM elements red. This creates a problem
if an EM element is contained within an H1
element, since it would not stand out as I would like. So, by using the
H1 EM selector, I specify that all EM elements
contained within H1 elements should be rendered green
instead of red. If you ignore the tasteless colors, the effect is exactly
what we want.




