DEV Community

Cover image for What are :nth-child & :nth-of-type Selectors.
Youssef Zidan
Youssef Zidan

Posted on • Edited on

What are :nth-child & :nth-of-type Selectors.

:nth-child Selector.

The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent.

where n can be a number, a keyword, or a formula.

selector:nth-child(integer)

Select a specific child.

:nth-child(integer)

:nth-child(integer)

selector:nth-child(n).

Selects all children.

:nth-child(n)

selector:nth-child(2n).

Selects every second child.

:nth-child(2n)

selector:nth-child(3n).

Selects every third child.

:nth-child(3n)

selector:nth-child(n+3).

Selects the third child, as well as all subsequent children.

:nth-child(n+3)

selector:nth-child(-n+3).

Selects the first three children.

:nth-child(-n+3)

selector:nth-child(2n+5).

Starting from child number 5, Select every second child.

:nth-child(2n+5)

selector:nth-child(-2n+5).

Select every second child until child number 5.

:nth-child(2n+5)

selector:nth-child(odd).

Selects odd children.

:nth-child(odd)

selector:nth-child(even).

Selects even children.

:nth-child(even)

:nth-of-type Selector.

The :nth-of-type(n) selector works the same but of a particular type.

Example

html

<div class="container"> <div class="parent"> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <div class="child"></div> <span class="child"></span> <span class="child"></span> <span class="child"></span> <span class="child"></span> <span class="child"></span> </div> </div> 
Enter fullscreen mode Exit fullscreen mode

css

.container{ display: flex; align-items: center; justify-content: center; height: 20%; } .parent { display: flex; align-items: center; justify-content: space-around; width: 100%; } .child, span { height: 50px; width: 50px; background-color: lightgray; } .child:nth-of-type(1){ background-color: darkblue; } 
Enter fullscreen mode Exit fullscreen mode

Output

Select the first element of each type div and span.
:nth-of-type(1)


LinkedIn

Top comments (1)

Collapse
 
manoharreddyporeddy profile image
Manohar Reddy Poreddy

Detailed information & Excellent presentation.
Great post.