Pseudo-classes and Pseudo-elements 35
These rules are much easier to demonstrate than they are to explain.
I’ll demonstrate the difference between them with the following example
(text has been truncated for clarity):
<div>
<h2>The Picture of Dorian Gray</h2>
<p>The artist is the creator...</p>
<p>To reveal art and conceal the artist...</p>
<p>The critic is he who can translate...</p>
</div>
And in my style sheet I’ll use these two rules:
p:nth-child(2n) { font-weight: bolder ; }
p:nth-of-type(2n) { font-weight: bolder; }
You can see the differing result of the two rules in Figure 4-1. In the
example markup, the div element has a total of four child elements: one
h2 and three p. The :nth-child(2n) selector in rule makes bold every
second child (the first and third paragraphs), as seen in the box on the
left. Compare that to the box on the right, which has rule applied; the
:nth-of-type(2n) selector ignores the h2 and applies a bold weight to every
second instance of the three elements of type p—that is, only the second
paragraph.
Figure 4-1: Comparing the result of using the :nth-child() selector (left) with
:nth-of-type() (right)
As I mentioned before, and as you can no doubt deduce from the previ-
ous examples, :nth-child() and :nth-of-type() have a fair bit of overlap, and
you can often use them interchangeably, as I do in the following example.
The table on the left of Figure 4-2 shows the five-day weather forecast
for London (so temperatures are given in degrees Celsius—0°C equals
32°F). These figures were taken in January—it’s not always this cold here!
All of the information I want to convey is in the table, but without any defi-
nition of rows, I find the table difficult to read.
Now compare this table to the one on the right in the same Figure 4-2.
Here, I used the technique known as zebra striping to aid the eye along the
row, making the data much more readable to me.