CSS :nth-last-of-type()

The CSS :nth-last-of-type(N) pseudo-class is used when we need to select Nth elements of specified type, from the last of its parent. For example, the following CSS code, applies style to second-last child element of its parent, of type P:

p:nth-last-of-type(2) {color: purple;}

CSS :nth-last-of-type() Example

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

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

This para one.

This is para two.

This is para one, inside DIV.

This is para two, inside DIV.

This is para three, inside DIV.

This is para two, from last.

This is para one, from last.

To apply styles to every 3rd element, from the last, use following code:

p:nth-last-of-type(3n) {declarations}

To apply styles to every even/odd element from last, use following code:

p:nth-last-of-type(even) {declarations}
p:nth-last-of-type(odd) {declarations}

CSS Online Test


« Previous Tutorial Next Tutorial »