Question

What is "nth-of-type" in CSS?

Answer and Explanation

The :nth-of-type() pseudo-class in CSS is a powerful selector that allows you to target elements based on their position within a group of siblings of the same type. Unlike :nth-child(), which considers all sibling elements, :nth-of-type() only counts elements of the same tag name.

Here's a breakdown of how it works:

Syntax:

selector:nth-of-type(an+b) { / CSS rules / }

Where:

- selector: The element you want to target (e.g., p, li, div).

- an+b: An expression that determines which elements to select. a and b are integers, and n is a counter that starts at 0.

Common Use Cases:

1. Selecting Every nth Element:

- p:nth-of-type(2n): Selects every even-numbered paragraph.

- li:nth-of-type(3n): Selects every third list item.

2. Selecting Specific Elements:

- div:nth-of-type(1): Selects the first div element among its siblings.

- h2:nth-of-type(4): Selects the fourth h2 element among its siblings.

3. Selecting Elements from the End:

- li:nth-of-type(n+3): Selects all list items starting from the third one.

- li:nth-of-type(n+3):nth-of-type(-n+5): Selects the third, fourth and fifth list items.

4. Using Keywords:

- p:nth-of-type(odd): Selects all odd-numbered paragraphs.

- p:nth-of-type(even): Selects all even-numbered paragraphs.

Key Differences from :nth-child():

- :nth-child() selects elements based on their position among all siblings, regardless of their tag name.

- :nth-of-type() selects elements based on their position among siblings of the same tag name.

Example:

Consider the following HTML:

<div>
  <p>First paragraph</p>
  <span>First span</span>
  <p>Second paragraph</p>
  <p>Third paragraph</p>
  <span>Second span</span>
</div>

- p:nth-of-type(2) will select "Second paragraph" because it's the second paragraph among its siblings.

- p:nth-child(2) would not select any paragraph because the second child is a span.

In summary, :nth-of-type() is a versatile tool for styling specific elements within a group of similar elements, making it ideal for creating complex layouts and designs.

More questions