ul:nth-child(2n+1){background-color: red;}
This translates to “Group the children (the lielements within the list in this
case) by twos(2n). Then apply the style only to the first element in this
grouping.” To get your head around this brain-twister, it helps to compare
that code to another example. The following turns every fourth list item red:
ul:nth-child(4n+1){background-color: red;}
Instead of specifying a pattern mathematically like the 4n+1 value, you
can instead use odd and evenas values rather than numbers to affect
every other descendant, like this:
ul:nth-child(even){background-color: red;}
You can count up from the bottom of a group with the nth-last-child
selector. You can also create groups when elements are mixed together
(they’re all siblings, all children of the same parent, but you want to just
specify a style for, say, the headlines rather than the paragraphs). For that,
use the nth-of-typeselector. CSS also offers a combo of the previous two
types: nth-last-of-type.
The variety of selectors goes on. The emptyselector selects barren elements
(elements that have no children). First-of-type (or last-of-type) selec-
tors provide a style for only the first or last child. For example, to italicize the
first list item in each list, try this:
ul:first-of-type{text-style: italic;}
Ever inventive, the CSS governing board also offers a none selector:
nth-of-none. It selects nothing. (Just kidding about this last one.)
278 Part IV: Advanced CSS Techniques