HTML and CSS Reference
In-Depth Information
Figure 1-31. Styling second children
ready to serve. (This does not mean the 93rd ordered list among its siblings; see the
next section for that.)
More powerfully, you can use simple algebraic expressions in the form a n + b or a n −
b to define recurring instances, where a and b are integers and n is present as itself.
Furthermore, the + b or b part is optional and thus can be dropped if it isn't needed.
Let's suppose we want to select every third list item in an unordered list, starting with
the first. The following makes that possible, as shown in Figure 1-32 .
ul > li:nth-child(3n + 1) {text-transform: uppercase;}
Figure 1-32. Styling every third list item
The way this works is that n represents the series 0, 1, 2, 3, 4, …and on into infinity.
The browser then solves for 3 n + 1, yielding 1, 4, 7, 10, 13, …and so on. Were we to
drop the + 1 , thus leaving us with simply 3n , the results would be 0, 3, 6, 9, 12, …and
so on. Since there is no zeroth list item—all element counting starts with one, to the
likely chagrin of array-slingers everywhere—the first list item selected by this expres-
sion would be the third list item in the list.
Given that element counting starts with one, it's a minor trick to deduce that :nth-
child(2n) will select even-numbered children, and either :nth-child(2n+1) or :nth-
child(2n-1) will select odd-numbered children. You can commit that to memory, or
you can use the two special keywords that :nth-child() accepts: even and odd . Want
to highlight every other row of a table, starting with the first? Here's how you do it, as
shown in Figure 1-33 .
tr:nth-child(odd) {background: silver;}
 
Search WWH ::




Custom Search