Home » Web » CSS » CSS and the selector nth-child

CSS and the selector nth-child

You may want to have special style for specific position. Maybe you want to have the first division different or having every 3 rows something different.

This can be done with nth-child selector of CSS.

Let’s start with a small example :

ul>li:nth-child(3) {  
  color: red;
}

This example will take the third li element that is directly under an ul element and make it’s font color to red.

The parameter, when specified with an integer, represent the position of the occurrence of the element. In the example above, 3 is specified, so the third element will be red.

nth-child is power full because you can use the variable “n” to specify the index of the element.

ul>li:nth-child(2n+1) {  
  background-color: red;
}

This second example of nth-child has 2n+1 has parameter. That mean that it will start at the position 1 (every sequence start at 1 not 0) and 2n mean 2 multiply by the index. So if we have the following code:

<ul>
  <li>n=0</li>
  <li>n=1</li>
  <li>n=2</li>
  <li>n=3</li>
  <li>n=4</li>
  <li>n=5</li>
</ul>

2n+1 will be for the first line : 2×0+1 = 1. So the first li will have the style, the first one will be 1. Then we have 2×1+1 = 3. The second row won’t have any style, the third one yes and so on.

To conclude, you have to remember that n start at 0 but the first element is 1. As we have seen with the ul/li example, the n=0 was coloured because n=0+1 = one, which is the first li of the ul collection.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.