Using nth-child CSS selectors

 

What is nth-child CSS Selectors?

To select any element inside your DOM (Document Object Model) there are lots of CSS selectors. And nth-child is one of them, more smarter, handy and useful to use.

By nth-child you can select any *th (1st, 2nd, 3rd, 4th........nth) element of your HTML DOM. Let’s see how we can use it:

Usage of nth-child in CSS

nth-child pseudo-selector define the number-th of your targetted element.
i.e: You have a list item like the following :

<ul>
    <li>First list item</li>
    <li>Second List Item</li>
    <li>Third List Item</li>
    <li>Fourth List Item</li>
    <li>Fifth List Item</li>
    ------------------------
    ------------------------
    <li>n-number List Item</li>
</ul>

In the above HTML code snippet there is total 5 <li> elements. Generally to select all <li> element we used –

li{
    color: red;
}

The above code will make all text inside <li> element in red color But what you should do if you want to format only 3rd or 5th or 4th element? In this case we will use our magic CSS pseudo-selector nth-child.

Let’s assume we will make the color of 4th <li> element red. To accomplish this task we need to write the following CSS :

li:nth-child(4){
    color: red;
 }

 

The above code will make red color to the 4th <li> element

Also if you want to select all odd(th) number of <li> element then you need to write –

li:nth-child(odd){
    color: red;
 }

 

the above code will make red color to 1st, 3rd and 5th <li> element. In the same way you can also select all even element to select 2nd and 4th <li> element with the following CSS code snippet.

Also you can provide any equation as argument for nth-child selector. Suppose we will select 3n+1(th) *<li>* element from our above HTML code. Then we need to write the following CSS :

li:nth-child(3n+1){
     color: red;
  }

 

*note: where n = 0, 1, 2, 3, …… *

So in that above CSS code our (3n+1 = 1*st*) element will be red color. Cause the value of n starts from Zero. So that 3x0 + 1 = 1 for first element and 3x1 + 1 = 4 for 4th element.. this will continue like this.

Now it’s time to try it yourself!!

Shaharia is a professional software engineer with more than 10 years of experience in the relevant fields. Digital ad certified, cloud platform architect, Big data enthusiasts, tech early adopters.

Site Footer