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



CSS :nth-of-type() pseudo-class matches elements based on their position among siblings of the same type (tag name).

Syntax

:nth-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-of-type() Example

Here is an example of how to use the :nth-of-type() selector to style the second span element −

<html>
<head>
<style>
   span:nth-of-type(2) {
      background-color: pink;
      color: blue;
   }
</style>
</head>
<body>
   <p>This is a <b>p</b> tag. </p>
   <span>This is first <b>span</b> tag.</span>
   <p>This is a <b>p</b> tag. </p>
   <span>This is second <b>span</b> tag</span>
   <p>This is a <b>p</b> tag. </p>
</body>
</html>

Here is an example of how to style odd paragraphs −

<html>
<head>
<style>
   p:nth-of-type(2n+1) {
      background-color: pink;
      color: blue;
   }
</style>
</head>
<body>
   <p>This is first <b>p</b> tag. </p>
   <div>This is first <b>div</b> tag.</div>
   <p>This is second <b>p</b> tag.</p>
   <p>This is third <b>p</b> tag.</p>
   <p>This is fourth <b>p</b> tag.</p>
   <div>This is second <b>div</b> tag..</div>
</body>
</html>
Advertisements