nth-last-child pseudo-class
The nth-last-child pseudo-class selects
an element that is the nth child of its parent,
starting from the end. It behaves similarly to
nth-child,
only counting from the end.
Syntax
selector:nth-last-child(число | odd | even | expression) {
}
Values
| Value | Description |
|---|---|
| number |
A positive number starting with 1.
Specifies the number of the element we want
to access. Numbering of elements starts
from 1.
|
odd |
Odd elements. |
even |
Even elements. | expression |
You can create special expressions with
the letter n, which stands for all integers
from zero (not one) to infinity. So,
2n means all even numbers (starting
from the second).
How to understand this? We substitute into n sequentially the numbers from
0 and so on: if n = 0, then 2n
will give 0 - there is no such element
(numbering of elements starting from 1),
if n = 1, then 2n gives 2 - the second
element, if n = 2, 2n gives 4 - the
fourth element. If you write 3n, it
will be every third element
(starting from the third),
and so on.
|
Example
In this example, we will make red the li
that is the 4th child from the end
of its parent:
<ul>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
</ul>
li:nth-last-child(4) {
color: red;
}
:
Example
Now let’s make red all the even li
from the end:
<ul>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
</ul>
li:nth-last-child(even) {
color: red;
}
:
Example
Now we’ll make red all the odd li
from the end:
<ul>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
</ul>
li:nth-last-child(odd) {
color: red;
}
:
Example
Now we’ll make red every third li
from the end:
<ul>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
<li>list item</li>
</ul>
li:nth-last-child(3n) {
color: red;
}
: