HTML and CSS Reference
In-Depth Information
That's all great, but what if you want to match images that are the only images inside
hyperlinks, but there are other elements in there with them? Consider the following:
<a href="http://w3.org/"><b>•</b><img src="w3.png" alt="W3C"></a>
In this case, we have an
a
element that has two children: a
b
and an
img
. That image,
no longer being the only child of its parent (the hyperlink), can never be matched
using
:only-child
. However, it
can
be matched using
:only-of-type
. This is illustrated
in
Figure 1-26
.
a[href] img:only-of-type {border: 5px solid black;}
<a href="http://w3.org/"><b>•</b><img src="w3.png" alt="W3C"></a>
<a href="http://w3.org/"><span><b>•</b><img src="w3.png" alt="W3C"></span></a>
Figure 1-26. Selecting images that are the only sibling of their type
The difference is that
:only-of-type
will match any element that is the only of its type
among all its siblings, whereas
:only-child
will only match if an element has no siblings
at all.
This can be very useful in cases such as selecting images within paragraphs without
having to worry about the presence of hyperlinks or other inline elements:
p > img:only-of-type {float: right; margin: 20px;}
As long as there aren't multiple images that are children of a paragraph, then the image
will be floated. You could also use this pseudo-class to apply extra styles to an
h2
when
it's the only one in a section of a document.
section > h2 {margin: 1em 0 0.33em; font-size: 180%; border-bottom: 1px solid gray;}
section > h2:only-of-type {font-size: 240%;}
Given those rules, any
section
that has only one child
h2
will have it appear larger than
usual. If there are two or more
h2
children to a
section
, neither of them will be larger
than the other. The presence of other children—whether they are other heading levels,
paragraphs, tables, paragraphs, lists, and so on—will not interfere with matching.
Selecting first and last children
It's pretty common to want to apply special styling to the first or last children of an
element. The most common example is styling a bunch of navigation links into a tab
bar, and wanting to put some special visual touches on the first or last tabs (or both).
In the past, this was done by applying special classes to those elements. Now we have
pseudo-classes to carry the load for us.