HTML and CSS Reference
Some Serious CSS
Want to see another, more advanced way to add color to every other row of a table? It's called the nth-child
pseudo-class . Remember, pseudo-classes are used to style elements based on their state (like the a:hover
pseudo-class we used in Head First Lounge, which styles a link if the user is hovering the mouse over the link).
For the nth-child pseudo-class, that state is the numerical order of an element in relation to its sibling elements.
Let's look at an example of what that means:
This is the first child…
…the thi rd child…
Let's say you want to select the even paragraphs (that is, paragraphs 2 and 4) so they have a red
background color, and the odd paragraphs so they have a green background color. You do that like this:
Para graphs 2 a nd 4 will be red…
As you might guess from the name “nth-child”, this pseudo-class is even more flexible
than just selecting odd and even items nested in an element. You can also specify simple
expressions that use the number n to give you a wide variety of options in selecting elements.
For instance, you can also select the even and odd paragraphs like this:
S elects even-
n umbere d <p>s
If n=0 , then 2n= 0 (no
paragr aph), and 2 n+1 is 1, whi ch
is the first paragr aph.
Se lects o dd-
nu mbered <p>s