HTML and CSS Reference
In-Depth Information
Contextual selectors take advantage of the general rule that the more specifi c style is
applied in preference to the more general. For instance, the styles
section h1 {color: red;}
h1 {color: blue;}
would result in any h1 heading text nested within a section element appearing in red,
even though the last style sets the text color to blue. The more specifi c style using the
contextual selector takes precedence over the general style in which no context has been
given.
Contextual selectors also can be listed with other selectors. The following style rule is
applied both to strong elements nested within list items and to h2 headings:
li strong, h2 {color: blue;}
The parent/descendant form is only one example of a contextual selector. Figure 3-20
describes some of the other contextual forms supported by CSS.
Figure 3-20
Contextual selectors
Selector
Description
*
Matches any element in the hierarchy
e
Matches any element, e , in the hierarchy
e1 , e2 , e3 , ...
Matches the group of elements e1 , e2 , e3 , ...
e f
Matches any element, f , that is a descendant of an element, e
e > f
Matches any element, f , that is a direct child of an element, e
e + f
Matches any element, f , that is immediately preceded by a sibling element, e
e ~ f
Matches any element, f , that is a sibling to an element, e
For example, the style rule
* {color: blue;}
uses the asterisk (*) selector—also known as the wildcard selector —to select all elements
in the document. The result is that the text of all elements in the document appears in
blue. On the other hand, the rule
p > em {color: blue;}
applies the blue text color only to emphasized text placed as a direct child of a para-
graph. Figure 3-21 provides additional examples of selectors applied to a document
tree. Selected elements are highlighted in red for each pattern. Remember that because
of style inheritance, any style applied to an element is passed down the document tree.
Thus, a style applied to a paragraph element is automatically passed down to elements
contained within that paragraph unless that style confl icts with a more specifi c style.
 
Search WWH ::




Custom Search