Pseudo-classes and Pseudo-elements 39
:only-child and :only-of-type
These two pseudo-classes are used to select elements in the document tree
that have a parent but either no sibling elements (:only-child) or no siblings
of the same type (:only-of-type). As with many of the previous pseudo-classes,
these two overlap substantially in function, but this next example illustrates
the difference between them. Take the following style rules:
p:only-of-type { font-style: italic; }
p:only-child { text-decoration: underline; }
and then apply them to this markup:
<h2>On Intelligence</h2>
<p>Arthur C. Clarke once said:</p>
<blockquote>
<p>It has yet to be proven that intelligence has any survival value.</p>
</blockquote>
You can see the result in Figure 4-6.
Figure 4-6: Comparing :only-child and :only-of-type
Both p elements are the only elements of their type in their level of the
document tree, so the :only-of-type rule selects both and italicizes them.
The p element inside the blockquote, however, is also the only child in its
level, so it’s also subject to the :only-child rule that applies the underline.
Using :only-of-type allows you to pick an element from among others,
whereas :only-child requires the element to sit alone.
Other Pseudo-classes
In addition to the structural pseudo-classes discussed so far in this chapter,
CSS3 introduces a number of pseudo-classes that allow you to select ele-
ments based on other criteria. These include link destinations, user inter-
face elements, and even an inverse selector that permits selection based on
what an element isn’t!