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

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

Take, for example, the following markup:

<div>
<p>Lorem ipsum.</p>
<p>Dolor sit amet.</p>
</div>

The first of the two p elements is the first child of the div element. That’s
obvious from the document tree, but the document tree doesn’t provide any
information that would allow you to apply a rule only to that element. CSS2
introduced the :first-child pseudo-class for exactly that reason:

E:first-child {...}

This pseudo-class allows you to make a selection based on informa-
tion that exists but isn’t provided as an attribute of the element—the exact
purpose of a pseudo-class. Since :first-child was introduced in CSS2, it has
been the only pseudo-class of its type. But CSS3 extends the range greatly
with the introduction of 11 new structural pseudo-classes.

The :nth-* Pseudo-classes


Four of the new pseudo-classes are based on a count value used to find an
element’s position in the document tree; for this count, you use the syntax
:nth-*. Note that I’ve used the asterisk here in place of a number of differ-
ent values, each of which I’ll introduce throughout the rest of this chapter.
The basic syntax of the :nth-* pseudo-classes is quite straightforward.
By default, n represents a number that begins at 0 and increments by 1 (1, 2,
3, etc.). Another integer can be passed into it as a multiplier. For example,
2n is every multiple of 2 (2, 4, 6, etc.), 3n is every multiple of 3 (3, 6, 9, etc.),
and so on:

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

The first example uses the default value n, so all elements of type E
would be selected; in practice, this is the same as using a simple element
selector. The next example selects every other E element, and the final
example selects every third element of type E.
You may also use the mathematical operators for plus (+) and minus (−).
So 2n+1 selects every multiple of two plus one (1, 3, 5, etc.), and 3n-1 selects
every multiple of three minus one (2, 5, 8, etc.):

E:nth-*(n+1) {...}
E:nth-*(2n+1) {...}
E:nth-*(3n-1) {...}
Free download pdf