CSS :nth-last-child()

The CSS :nth-last-child(N) pseudo-class is used when we need to select Nth child element of their parent, but from the last. For example, the following CSS code, applies style to the second-last TR element of TABLE:

tr:nth-last-child(2) {background-color: green; color: white;}

CSS :nth-last-child() Example

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p:nth-last-child(2) {background-color: #ccc; text-align: center; padding: 10px;}
   </style>
</head>
<body>

   <p>This para one.</p>
   <p>This is para two.</p>
   <p>This is para three.</p>
   <p>This is para four.</p>
   <p>This is para five.</p>
   
</body>
</html>
Output

This para one.

This is para two.

This is para three.

This is para four.

This is para five.

Note - The :nth-last-child(N) selects Nth element from last, regardless the type and parent.

Similar to :nth-child(N) pseudo-class, we can also use formula or even/odd keyword for N to apply the style, based on the requirement. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p:nth-last-child(even) {background-color: rgb(31, 83, 83); color: white; padding: 10px;}
      p:nth-last-child(odd) {background-color: rgb(54, 133, 133); color: white; padding: 10px; text-align: right;}
   </style>
</head>
<body>

   <p>This para one.</p>
   <p>This is para two.</p>
   <p>This is para three.</p>
   <p>This is para four.</p>
   <p>This is para five.</p>
   
</body>
</html>
Output

This para one.

This is para two.

This is para three.

This is para four.

This is para five.

We can also apply any formula made with numbers and n like 2n+1, 4n, 3n+2 etc. to apply styles to every specified child element from the last of their parent. For example, the following example, applies style to every 2nd P element from the last:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      p:nth-last-child(2n) {background-color: rgb(31, 83, 83); color: white; padding: 10px;}
   </style>
</head>
<body>

   <p>This para one.</p>
   <p>This is para two.</p>
   <p>This is para three.</p>
   <p>This is para four.</p>
   <p>This is para five.</p>
   
</body>
</html>
Output

This para one.

This is para two.

This is para three.

This is para four.

This is para five.

CSS Online Test


« Previous Tutorial Next Tutorial »