The Book of CSS3 - A Developer\'s Guide to the Future of Web Design (2nd edition)

(C. Jardin) #1
Pseudo-classes and Pseudo-elements 37

:first-of-type, :last-child, and :last-of-type


If you take a look at the tables in Figure 4-2, you’ll notice that the text in
the Weather column is left-aligned, whereas the other columns are center-
aligned. I did this using the :first-of-type pseudo-class, which is similar to
the :first-child selector introduced in CSS2, but with the same difference
in type and child that you’ve seen so far in this chapter.
As you’re no doubt aware, the :first-child pseudo-class is a selector
used to apply rules to an element that is the first child of its parent. As
with :nth-of-type(), however, :first-of-type is more specific, applying only
to the element that is the first child of the named type of its parent. A pair
of counterpart pseudo-classes is also available, :last-child and :last-of-type,
which—as you might have guessed—select the last child element or the last
child element of that type, respectively, of the parent.
In the weather table examples in the previous section, the markup for
each row in the table body is structured like this:

<tr>
<th>Sun</th>
<td>Sunny</td>
<td>8</td>
<td>4</td>
<td>8</td>
</tr>

I want to left-align the content of the second column, so I can’t use
:first-child here as the first child is a th. Instead, I use the :first-of-type
selector:

tbody td:first-of-type { text-align: left; }

I’ll show two more examples to demonstrate the difference clearly. I’ll
apply both of the examples to the same chunk of markup (I’ve truncated
the text for clarity):

<div>
<h2>Wuthering Heights</h2>
<p>I have just returned...</p>
<p>This is certainly...</p>
<p>In all England...</p>
<h3>By Emily Bronte</h3>
</div>

In the first example, I use :first-child and :last-child, as shown here:

:first-child { text-decoration: underline; }
:last-child { font-style: italic; }

The result is shown in Figure 4-4. The h2 element is the first child of the
div, so it has an underline applied to it. The last child of the div is the h3 ele-
ment, so that is italicized. All quite straightforward.
Free download pdf