Web Design

CSS Tutorial #1 :nth-child() Selector

nth-child() Selector

The :nth-child() selector in CSS is a powerful tool for selecting elements based on their position within a parent element. It allows you to target specific child elements using a variety of formulas and patterns. In this guide, we’ll explore the different ways you can use the :nth-child() selector to achieve various selection criteria.
Basic Syntax: The basic syntax of the :nth-child() selector is as follows:


The formula inside the parentheses determines which elements should be selected. It uses the n keyword to represent the position of an element and allows for addition, subtraction, and multiplication operations.

Selecting Specific Positions:

You can target elements at specific positions using the :nth-child() selector. Here are some examples:

  • Select the 1st child element:
  • Select the 3rd child element:

Selecting Patterns:

The :nth-child() selector also allows you to select elements based on patterns or intervals. Here are a few examples:

  • Select even-numbered elements:
  • Select odd-numbered elements:
  • Select every 3rd child element:
  • Select every 2nd child element starting from the 4th position:
  • Select elements between the 2nd and 5th positions (inclusive):

Selecting Groups of Elements:

You can also select groups of elements using the :nth-child() selector. Here’s how:

  • Select the first two child elements:
  • Select the last three child elements:

Combining Selectors:

The :nth-child() selector can be combined with other selectors to narrow down the selection further. For example:

  • Select every 2nd div element:
  • Select every 3rd paragraph inside a section:
section p:nth-child(3n)
  • Select the 2nd and 3rd li elements inside an unordered list:
ul li:nth-child(n+2):nth-child(-n+3)

Remember, the :nth-child() selector is zero-based, meaning the first child element has an index of 0.These examples demonstrate the versatility of the :nth-child() selector. By understanding its syntax and combining it with other selectors, you can precisely target and style specific elements within your HTML structure.

Leave a Reply

Your email address will not be published. Required fields are marked *