CSS pseudo-class - :nth-last-of-type()



CSS :nth-last-of-type() pseudo-class selects one or more elements based on their position among their siblings of the same type, counting from the last.

Syntax

:nth-last-of-type( | even | odd) {
   /* ... */
}

Possible Values

  • odd − This value represents all odd-numbered (such as, 1,3,5..etc) sibling elements in a series counting from the end.

  • even − This value represents all even-numbered (such as, 2,4,6...etc) sibling elements in a series counting from the end.

  • functional notation (<an+b>) − This value represents every an+b-th child element in a series counting from the end of its parent container, where a is a positive integer, and n is a counter variable that starts from 0. b is another positive integer.

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

Here is an example demonstrating use of :nth-last-of-type() selector to style the third p element from bottom −

<html>
<head>
<style>
   p:nth-last-of-type(3) {
      background-color: pink;
      color: blue;
   }
</style>
</head>
<body>
   <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </p>
   <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. </p>
   <p>Contrary to popular belief, Lorem Ipsum is not simply random text.</p>
   <p>The standard chunk of Lorem Ipsum used since the 1500s</p>
   <p>Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero</p>
   <p>Lorem Ipsum is therefore always free from repetition,</p>
</body>
</html>  

Here is an example of how to style odd and even paragraphs in a different way −

<html>
<head>
<style>
   p:nth-last-of-type(odd) {
      background-color: pink;
      color: blue;
   }
   p:nth-last-of-type(even) {
      background-color: greenyellow;
      color: red;
   }
</style>
</head>
<body>
   <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
   <p>Contrary to popular belief, Lorem Ipsum is not simply random text.</p>
   <p>The standard chunk of Lorem Ipsum used since the 1500s</p>
   <p>Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero</p>
   <p>Lorem Ipsum is therefore always free from repetition,</p>
</body>
</html>
Advertisements