The pseudo-class :nth-child
is often used in tables or lists to differentiate even rows from odd ones:
li:nth-of-type(2n) {
background-color: #ccc;
}
<ul>
<li>elemento1</li>
<li>elemento2</li>
<li>elemento3</li>
<li>elemento4</li>
</ul>
Or to select a specific child element:
li:nth-of-type(3) {
background-color: #F00;
}
<ul>
<li>elemento1</li>
<li>elemento2</li>
<li>elemento3</li>
<li>elemento4</li>
</ul>
However, it has a more complex syntax, I have seen cases of this style:
p:nth-child(4n+2)
I don't quite understand what exactly it does and what practical uses it can have.
The pseudoclass
:nth-child()
selects siblings that meet a certain condition defined in the formulaan + b
.a
andb
must be integers,n
it is a counter. The groupan
represents a cycle, every few elements it repeats;b
indicates where we start counting from.Let's see it with examples to understand it better:
Select every three elements starting with the second:
Select every three elements:
When
b=0
it can be omitted remaining:Select the second element:
When
a=0
it can be omittedan
and we are left with:Select every two elements up to the sixth:
We can also use negative numbers. When
a
it is negative, the cycle is only repeated untilb
:Select all elements up to the sixth:
yes
a=1
ora=-1
we can omita
:Select the first element:
If what we wanted was to select the first element, we can use the pseudoclass
first-child
, a specific pseudoclass for this purpose.It would be equivalent to using any of the following pseudo-classes:
nth-child(0n+1)
nth-child(1)
Select the last element:
Similarly, we can also select the last element using the pseudo-class
last-child
:Keywords:
To select even and odd elements we also have the keywords
odd
andeven
:Select the nth element of a given type:
Sometimes it happens that we want to select, for example, the second child paragraph of a paragraph
div
that has several different child-elements and we try something like this:It doesn't work because it
p:nth-child(2)
looks for the second child that is also ap
and since the second child is not ap
the condition is not met and it does nothing.Could that be done somehow? Yes, but with another pseudo-class called
:nth-of-type()
that works basically the same but only counts the elements of the chosen type.