CSS :nth-of-type

The :nth-of-type() CSS pseudo-class matches the elements based on their position within a parent element. It allows you to target specific elements using a formula that determines the element's position.

The syntax for using the :nth-of-type() selector is:

selector:nth-of-type(formula) {
  /* styles */
}

Where selector is the element you want to target and formula is a specific type of expression to target elements.

Let's go through some examples to understand how the :nth-of-type() selector works:

Result:

Example 1: Target every third paragraph element

<style>
  p:nth-of-type(3n) {
    color: blue;
  }
</style>

This CSS rule will target every third paragraph element and change its color to blue.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris.

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum.

Result:

Example 2: Target the first and fifth list items

<style>
  li:nth-of-type(1), li:nth-of-type(5) {
    font-weight: bold;
  }
</style>

This CSS rule will target the first and fifth list items and make their font weight bold.

  • Item 1
  • Item 2
  • Item 3
  • Item 4
  • Item 5

By using the :nth-of-type() selector, you can target specific elements within a parent element based on their position. Experiment with different formulas and see how you can style your webpage effectively.