Differences between the CSS properties: nth-child and nth-of-type

I will try to clarify the difference between the nth-child and nth-of-type.
p:nth-child(1): Means that is the first child of any parent and is of type paragraph.
p:nth-of-type (1): Means that is the first appearance of the type paragraph within any parent.

This example will clarify the things a little bit:

<style>
   p:nth-child(1){background:#f00;}
   p:nth-of-type(1){background:#0f0;}
</style>
<div>
   <div>first child</div>
   <p>second child and first element of class "p"</p> <!-- GREEN -->
   <p>third child and second element of class "p"</p>
   <p>fourth child and third element of class "p"</p>
</div>

In this example the parent is the first <div>, and only the nth-of-type(1) property will work setting the background to green (#0f0). The nth-child(1) property didn’t work because the first child it’s actually a <div>, not a paragraph.

Even and odd elements

In both properties we can use the params odd or even to make easier styling lists or other elements:

   li:nth-child(even){
       background:#f00;
   }
   li:nth-of-type(odd){
       background:#0f0;
   }
<ul>
    <li>row 1</li><!-- GREEN -->
    <li>row 2</li><!-- RED-->
    <li>row 3</li><!-- GREEN -->
    <li>row 4</li><!-- RED-->
</ul>

This will affect the code setting the background red(#f00) in to the even <li> elements and green(#0f0) in to the odd <li> elements.

Numeric rules

You can use other rules like nth-child(3n+3). The “n” behaves like a counter, starting from 0. These would be the elements affected by this property:
(3 x 0) + 3 = 3 = 3rd Element
(3 x 1) + 3 = 6 = 6th Element
(3 x 2) + 3 = 9 = 9th Element

Other example using nth-child(2n-1):
(2 x 0) – 1 = – 1 = nothing
(2 x 1) – 1 = 1 = 1st Element
(2 x 2) – 1 = 3 = 3rd Element

Comments 1

Leave a Reply

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