HTML and CSS Reference
In-Depth Information
SELECTING FROM THE END BACKWARD
You don't have to select from the top
down. You can select from the bottom up
with
:nth-last-child
. It works in the same
way as
:nth-child
:
li:nth-last-child(2n) {
background-color: #000;
}
The hypothetical values for
n
extend to
negative numbers, as can be seen if you
try this:
li:nth-last-child(2n+2) {
background-color: #000;
}
You'll notice that
2n+2
has results identical
to
2n
and to
2n-2
.
But if
n
is negative, different rules apply.
Now
n
will count backwards from the
elements you see; if there are six elements
it will count six back. So adding a fixed
number to it will move the range of
selected elements so that it selects that
number of visible elements. This selector
will target just the first three elements:
li:nth-child(-n+3) {
background-color: #000;
}