What is the nth-child() method in CSS?

The :nth-child() is a CSS pseudo-class selector that allows you to select elements based on the index (source order) inside their container.

A ​pseudo-class selector selects content based on its relationship with parent and sibling elements.

The :nth-child() takes only one argument as its input:

  • A number, keyword, or formula specifying the nth-child we want to select.

Additionally, we can ​specify the HTML element whose child we want to select through the :nth-child() method. If no such element is specified, then the :nth-child() method applies the input argument to all the elements in the HTML.

Syntax

svg viewer

Codes

The following examples demonstrate different arguments passed to the :nth-child() method.

1. Using a number as the argument

2. Using a keyword as the argument

3. Using a formula as the argument


Copyright ©2024 Educative, Inc. All rights reserved