HTML and CSS Reference
In-Depth Information
The terms “parent” and “child” are specific applications of the terms
ancestor
and
descendant
. There is a difference between them: in the tree view, if an element is exactly
one level above another, then they have a parent-child relationship. If the path from
one element to another is traced through two or more levels, the elements have an
ancestor-descendant relationship, but not a parent-child relationship. (Of course, a
child is also a descendant, and a parent is an ancestor.) In
Figure 1-15
, the first
ul
element is parent to two
li
elements, but the first
ul
is also the ancestor of every element
descended from its
li
element, all the way down to the most deeply nested
li
elements.
Also, in
Figure 1-15
, there is an anchor that is a child of
strong
, but also a descendant
of
paragraph
,
body
, and
html
elements. The
body
element is an ancestor of everything
that the browser will display by default, and the
html
element is ancestor to the entire
document. For this reason, the
html
element is also called the
root element
.
Descendant Selectors
The first benefit of understanding this model is the ability to define
descendant selec-
tors
(also known as
contextual selectors
). Defining descendant selectors is the act of
creating rules that operate in certain structural circumstances but not others. As an
example, let's say you want to style only those
em
elements that are descended from
h1
elements. You could put a
class
attribute on every
em
element found within an
h1
,
but that's almost as time-consuming as using the
font
tag. It's obviously far more effi-
cient to declare rules that match only
em
elements that are found inside
h1
elements.
To do so, write the following:
h1 em {color: gray;}
This rule will make gray any text in an
em
element that is the descendant of an
h1
element.
Other
em
text, such as that found in a paragraph or a block quote, will not be selected
by this rule.
Figure 1-16
makes this clear.
Figure 1-16. Selecting an element based on its context
In a descendant selector, the selector side of a rule is composed of two or more space-
separated selectors. The space between the selectors is an example of a
combinator
.
Each space combinator can be translated as “found within,” “which is part of,” or “that
is a descendant of,” but only if you read the selector right to left. Thus,
h1 em
can be
translated as, “Any
em
element that is a descendant of an
h1
element.” (To read the
selector left to right, you might phrase it something like, “Any
h1
that contains an
em
will have the following styles applied to the
em
.”)
You aren't limited to two selectors, of course. For example:
ul ol ul em {color: gray;}