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

(C. Jardin) #1

34 Chapter 4


The first example selects every element of type E except for the first
instance; the count for this would be 2, 3, 4, 5, and so on. The next example
selects every odd-numbered E element (1, 3, 5, and so on). The final example,
as just mentioned, selects elements in the sequence 2, 5, 8, and so on.
Two special keyword values, even and odd, are also available; you can use
these to replace 2n and 2n+1, respectively:

E:nth-*(even) {...}
E:nth-*(odd) {...}

Finally, it’s also acceptable to use 0n (that’s zero) as a value. It has no
use of itself but is very useful when combined with a mathematical operator,
as it allows you to pinpoint a single element without any recurrence. In fact,
for brevity, you can supply only the value after the mathematical operator.
For example, to select only the third element in a selector list, both of these
values are valid:

E:nth-*(0n+3) {...}
E:nth-*(3) {...}

With the basic syntax out of the way, let’s move on to the pseudo-classes
themselves.

:nth-child() and :nth-of-type()
Most of the new structural pseudo-classes allow you to select elements
based on either their position in the document tree in relation to their
parent element (-child) or their classification (-of-type). Often these
definitions overlap, but there are crucial differences between them.
The simplest examples of these pseudo-classes are :nth-child()
and :nth-of-type(). The first, :nth-child(), selects an element based on its
position in a count of the total number of children in its parent element;
:nth-of-type() bases its count not on the total children, but only on those
of the specified element type.

 E:nth-child(n) {...}
 E:nth-of-type(n) {...}
 E:nth-child(2n) {...}
x E:nth-of-type(2n) {...}

In this example, rules  and  are equivalent because the count value
(n) is left at the default; both of these simply select all child elements of type
E. The difference reveals itself in the later examples: in , :nth-child(2n)
selects all elements of type E from a count that includes all its siblings
but only where those elements are even-numbered. In x, by comparison,
:nth-of-type(2n) selects all even-numbered elements of type E from a count
that includes only those elements.
Free download pdf