HTML and CSS Reference
In-Depth Information
Therefore, if you want to select those
em
elements that are the first child of another
element, you write
em:first-child
.
The mirror image of
:first-child
is
:last-child
. If we take the previous example and
just change the pseudo-classes, we get the result shown in
Figure 1-28
.
p:last-child {font-weight: bold;}
li:last-child {text-transform: uppercase;}
<div>
<p>These are the necessary steps:</p>
<ul>
<li>Insert key</li>
<li>Turn key <strong>clockwise</strong></li>
<li>Push accelerator</li>
</ul>
<p>
Do <em>not</em> push the brake at the same time as the accelerator.
</p>
</div>
Figure 1-28. Styling last children
The first rule boldfaces any
p
element that is the last child of another element. The
second rule uppercases any
li
element that is the last child of another element. If you
wanted to select the
em
element inside that last paragraph, you could use the selector
p:last-child em
, which selects any
em
element that descends from a
p
element that is
itself the last child of another element.
Interestingly, you can combine these two pseudo-classes to create a version of
:only-
child
. The following two rules will select the same elements:
p:only-child {color: red;}
p:first-child:last-child {background: red;}
Either way, you'd get paragraphs with red foreground and background colors (not a
good idea, clearly). The only difference is in terms of specificity, which we'll cover later
in this topic.