HTML and CSS Reference
In-Depth Information
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:
<section>
<p>
This is the first child…
<p>
<p>
…the thi
rd child…
<p>
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:
p:nth-child(even) {
background-color: red;
}
p:nth-child(odd) {
background-color: green;
}
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:
<section>
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.
<p>
p:nth-child(2n) {
background-color: red;
}
p:nth-child(2n+1) {
background-color: green;
}
<p>
Se
lects o
dd-
nu
mbered
<p>s
<p>
<p>