HTML and CSS Reference
In-Depth Information
Contextual Selectors
So far, the only selectors you've studied involve either single elements or groups of ele-
ments in a comma-separated list. However, this approach doesn't take into account that
Web pages are structured documents in which elements are nested within other ele-
ments, forming a hierarchy of elements. Figure 3-19 shows an example of such a tree
structure for a Web page consisting of a few headings, a couple of paragraphs, and a few
text-level elements, all descending from the body element.
Figure 3-19
A sample hierarchy of page elements
To create styles that take advantage of this tree structure, CSS allows you to create
contextual selectors whose values represent the locations of elements within the hier-
archy. As with the folder structure discussed in Tutorial 2, elements in a Web page are
often referenced using their familial relationships. A parent element is an element that
contains one or more other elements, which are child elements of the parent. Two child
elements that share the same parent are referred to as sibling elements . Each child ele-
ment may contain children of its own and so forth down the hierarchy, creating a set of
descendant elements that are all descended from a common parent. The ultimate parent
element for the HTML fi le is the html element itself, and the parent element for all ele-
ments within the page body is the body element.
One commonly used selector that takes advantage of these familial relationships has
the form
parent descendant { styles }
where parent is the parent element, descendant is a descendant of the parent, and
styles are the style properties applied to the descendant element. For example, to dis-
play the text of all h1 headings found within a page header in blue, you could apply the
following style rule:
header h1 {color: blue;}
In this case, header is the parent element and h1 is the descendant element (because
it is contained within the header element). Any h1 heading that is not placed within a
page header is not affected by this style. Note that the descendant element does not have
to be a direct child of the parent; it can appear several levels below the parent in the
hierarchy. This style applies equally to the following HTML code:
<h1>Sunny Acres</h1>
Here, the h1 element is a direct child only of the hgroup element; but because it is
still a descendant of the header element, it would still appear in blue.
Search WWH ::

Custom Search