HTML and CSS Reference
In-Depth Information
<li>Row 3</li>
<li>Row 4</li>
<li>Row 5</li>
<li>Row 6</li>
Odd-numbered rows in this list can be colored gray by adding the following code:
li:nth-child(odd) { background-color:#ccc; }
Coloring the even rows is as easy as exchanging the keyword odd with even :
li:nth-child(even) { background-color:#ccc; }
These result in the lists shown in Figure 6-7 .
Figure 6-7. Zebra striping on even and odd numbered rows in a list being styled using :nth-
child(even) and :nth-child(odd) selectors
Additionally, nth- selectors include a pattern formula that allows different rows
from the even or odd ones to be selected. In place of even or odd , the formula an+b
can be used. The n equals the number of child elements to process (six rows in a list
in the prior case), with counting beginning at zero. The value of a is then multiplied by
each value of n , and b is added to that value. For example, in the formula 3n+1 , the
first row processed assigns a value of 0 to n , so the formula ends up being (3 × 0) + 1,
which equals 1, meaning the style applies to the first row. For the next row, the formula
becomes (3 × 1) + 1, which equals 4, meaning the style applies to the fourth row. Next
would be (3 × 2) + 1, equaling the seventh row. Figure 6-8 is the appearance of an un-
ordered list that had the following CSS rule applied:
li:nth-child(3n+1) { background-color:#cccccc; }
Search WWH ::

Custom Search