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 πŸ”¦

Pseudo selector :nth-child() explained interactively
Photo by KOBU Agency / Unsplash / Image / Image

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:

  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>

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:


Selects the first element


Selects the second element


Selects all odd elements


Selects all even elements


Selects every fifth element


Selects the fifth element


Selects the fourth element and from then on every third


Selects the first three elements


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 πŸ‘‡