CSS :nth-of-type()

The CSS :nth-of-type(N) pseudo-class is used when we need to select every Nth child elements of specified type, of its parent. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p:nth-of-type(2) {background-color: yellowgreen; font-weight: bold; padding: 10px;}
   </style>
</head>
<body>

   <p>This para one.</p>
   <p>This is para two.</p>
   <p>This is para three.</p>
   <div>
      <p>This is para one, inside DIV.</p>
      <p>This is para two, inside DIV.</p>
   </div>
   
</body>
</html>
Output

This para one.

This is para two.

This is para three.

This is para one, inside DIV.

This is para two, inside DIV.

Note - The value of n can also be a formula like 2n+1, that is nth-of-type(2n+1) to select alternate elements. The value of n (in 2n+1) starts with 0, and increments by 1, each time. Therefore 2n+1 gives 1, 3, 5, 7, and so on. In this way, the style will be applied to element at first, third, fifth, seventh, and so.

Similarly 3n+1 gives 1, 4, 7, 10, and so on. 3n+2 gives 2, 8, 11, 14, and so on. We can also use even/odd to apply the styles to alternate elements. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      tr:nth-of-type(even) {background-color: yellowgreen; color: whitesmoke}
      tr:nth-of-type(odd) {background-color: green; color: whitesmoke;}
      td {padding: 10px;}
   </style>
</head>
<body>

   <table>
      <tr>
         <td>one</td>
         <td>two</td>
         <td>three</td>
      </tr>
      <tr>
         <td>four</td>
         <td>five</td>
         <td>six</td>
      </tr>
      <tr>
         <td>seven</td>
         <td>eight</td>
         <td>nine</td>
      </tr>
      <tr>
         <td>ten</td>
         <td>eleven</td>
         <td>twelve</td>
      </tr>
      <tr>
         <td>thirteen</td>
         <td>fourteen</td>
         <td>fifteen</td>
      </tr>
   </table>
   
</body>
</html>
Output
one two three
four five six
seven eight nine
ten eleven twelve
thirteen fourteen fifteen

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!