Selectors
| Selector | Targets | Reading direction |
|---|---|---|
nth-child(n) |
Nth child element, of any type | From beginning to end |
first-child(n) |
First child element, whatever its type | |
nth-of-type(n) |
First occurrence of a specific child element | |
last-child(n) |
Last child element, whatever its type | From end to beginning |
last-of-type(n) |
Last occurrence of a specific child element |
n can take the following values:
- an integer (positive or negative)
- a keyword:
odd/even - an an + b formula, which I break down below
Reminder
The indexes of the elements that can be targeted by a selector start at 1.
n as an an + b formula:
Using a formula (an + b). Description: a represents the size of a cycle, n is a counter (starting at 0) and b is an offset value.
— http://www.w3schools.com/cssref/sel_nth-child.asp
- If n is positive, the selection goes in the direction initiated by the selector,
or if n is negative, the selection goes in the opposite direction of the one initiated by the selector; - An a value attached to n allows the selection to skip elements: 2n = every other element, 3n = every third element, etc.
- The b value shifts the selection at each iteration, also depending on its sign (positive in the direction of n, negative in the opposite direction of n).
Select the 1st element
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
li:nth-child(1) { }
ou
li:first-child { }
Select the last element
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
li:last-child { }
Select the second-to-last element
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
li:nth-last-child(2) { }
Select the 5th element
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
li:nth-child(5) { }
Select the first 3 elements
Here the selection of elements is steered toward zero, starting from three.
So the third, the second, and the first elements are selected.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
li:nth-child(-n+3) { }
Select all elements except the first 3
Here the selection of elements is steered toward infinity, starting from the fourth.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
li:nth-child(n+4) { }
Select the last 3 elements
Here, starting from the end, the selection of elements is steered toward zero, starting from the fourth.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
li:nth-last-child(-n+3) { }
ou
li:nth-last-child(n+8) { }
Select all elements except the last 3
Here the selection of elements is steered toward zero, starting from the fourth, counting from the end.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
li:nth-child(-n+7) { }
ou
li:nth-last-child(n+4) { }
Select every 4th element starting with the 1st
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
li:nth-child(4n+1) { }
Select even elements
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
li:nth-child(even) { }
ou
li:nth-child(2n) { }
Select odd elements
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
li:nth-child(odd) { }
ou
li:nth-child(2n+1) { }
