Pseudo selector :nth-child() explained interactively
At first glance, the selector still seems really complicated, but I'll show you how you can use it for your needs π¦
When it comes to web development, especially with regard to CSS, there are always problems that can usually be solved with standard CSS. The pseudo selector :nth-child()
regularly causes a lot of confusion. It is actually very useful, especially if you want to style many (child) elements in one element.
It's easier than it looks π€
At first glance, the selector still seems really complicated, even the MDN documentation can quickly confuse rather than enlighten. But if you take a closer look, the function is not that difficult to understand.
In concrete terms, it simply selects the nth child within an element. It can cover several variations (and also simple calculations). n
stands for any number.
Example of use π
Suppose we have a DIV with the ID Parent
and we want to select the child elements based on certain criteria so that we can give them a background-color
and a border-color
. We use the following markup for this:
div#parent:nth-child(n){
background-color: rgba(156,19,129, .75);
border-color: #2dd4bf;
}
<div id="parent">
<span id="div1">Test</span>
<span id="div2">Test</span>
<span id="div3">Test</span>
<span id="div4">Test</span>
</div>
Application cases π¨βπ»
:nth-child()
is therefore very suitable for selecting child elements according to a calculation. This can be used for alternating rows in tables, for example, or for lists or all elements with children. In general, there are the following options:
:nth-child(1)
Selects the first element
:nth-child(2)
Selects the second element
:nth-child(odd)
Selects all odd elements
:nth-child(even)
Selects all even elements
:nth-child(5n)
Selects every fifth element
:nth-child(+5)
Selects the fifth element
:nth-child(3n+4)
Selects the fourth element and from then on every third
:nth-child(-n+3)
Selects the first three elements
:nth-child(n)
Selects all elements
Interactive example π
So that you can understand the behavior, I have created an interactive example at StackBlitz, I have created an example in which the behavior can be illustrated interactively.
Has this little guide helped you to understand :nth-child()
? Do you already have some use cases of your own in mind or ideas? Let me know in the comments π