HTML and CSS Reference
In-Depth Information
Table 13-1.
Structural Pseudo-classes that Select First, Last, and Only Instances
Pseudo-class
Description
:first-child
Selects an element that is the first child of its parent.
:last-child
Selects an element that is the last child of its parent.
:only-child
Selects an element that is the
only
child of its parent and has no siblings.
:first-of-type
Selects an element that is the first sibling of its type.
:last-of-type
Selects an element that is the last sibling of its type.
:only-of-type
Selects an element that is the only sibling of its type. It can have other siblings, but not of
the same type.
The difference between the “child” and “of-type” pseudo-classes lies in the relationship of the target element
to its parent. The
:first-child
pseudo-class applies to the first element nested inside its parent, whereas the
:first-of-type
applies the first element of that particular type within its parent.
Take the following HTML markup in first-child.html in the ch13 folder:
<div id="aside">
<h3>Climate</h3>
<p>The Mediterranean has. . .</p>
<h3>Getting There</h3>
In this example, the “Climate” heading is the first child of the
aside<div>
, so it's selected by the following
style rule:
h3:first-child {
text-transform: uppercase;
}
■
In this case, you could use either
h3:first-child
or
h3:first-of-type
because the first child is always
the first element of its type. But the first element of its type is not always the first child, as you'll see shortly.
Tip
The “Getting There” heading is nested deeper inside the
<div>
, so it ignores the
h3:first-child
style rule.
As Figure
13-1
shows, only the first heading is converted to uppercase.