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

(C. Jardin) #1

36 Chapter 4


Figure 4-2: Weather forecast table (left) and better formatted for readability (right). Weather data from
http://bbc .co .uk/weather/


I achieved this technique with a single CSS3 declaration:

tbody tr:nth-of-type(even) { background-color: #DDD; }

In this example, I could have used :nth-child() instead, as in the markup
all of the child elements of tbody are of the same type: tr. Where every child
is of the same type, :nth-child() and :nth-of-type() are interchangeable.

:nth-last-child() and :nth-last-of-type()
The :nth-last-child() and :nth-last-of-type() pseudo-classes accept the
same arguments as :nth-child() and :nth-of-type(), except they are counted
from the last element, working in reverse. For example, say I want to use
some visual shorthand to show in my weather table that the forecasts for
days four and five are less certain than for the preceding days. You can see
how this would look in Figure 4-3.

Figure 4-3: Extra formatting using :nth-last-child()

Here I italicized the characters in the last two rows by using the
:nth-last-child() pseudo-class (although, once again, :nth-last-of-type()
would serve just as well in this example), passing an argument of -n+2:

tbody tr:nth-last-child(-n+2) { font-style: italic; }

I used the negative value (-n) to increment the count negatively, which
has the effect of acting in reverse. Because :nth-last-child() and :nth-last-
of-type() count backward through the tree, using a negative value here
makes the count go forward! The count starts at the last tr element in the
table and counts up in reverse order, so the last and penultimate lines are
the first two counted and are, therefore, italicized. This may seem counter-
intuitive, but it’ll become second nature as you traverse the document tree.
Free download pdf