HTML and CSS Reference
In-Depth Information
In the previous case, the first yellow
li
element will be the fourth. If you
just want to start counting from the first
li
element, you can use a simpler
expression:
ul li:nth-child(3n) {
color: yellow;
}
In this case, the first yellow
li
element will be the third, and every other
third after it. Now imagine you want to target only the first four
li
elements
within the list:
ul li:nth-child(-n+4) {
color: green;
}
The value of
:nth-child
can also be defined as “even” or “odd”, which
are the same as using “2n” (every second child) or “2n+1” (every second
child starting from the first), respectively.
:NTH-LAST-CHILD
The
:nth-last-child
pseudo-class works basically as the
:nth-child
pseudo-class, but it starts counting the elements from the last one.
Using one of the examples above:
ul li:nth-child(-n+4) {
color: green;
}
Instead of matching the first four
li
elements in the list, this selector will
match the
last
four elements.