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.
selector:nth-child(n).
Selects all children.
selector:nth-child(2n).
Selects every second child.
selector:nth-child(3n).
Selects every third child.
selector:nth-child(n+3).
Selects the third child, as well as all subsequent children.
selector:nth-child(-n+3).
Selects the first three children.
selector:nth-child(2n+5).
Starting from child number 5, Select every second child.
selector:nth-child(-2n+5).
Select every second child until child number 5.
selector:nth-child(odd).
Selects odd children.
selector:nth-child(even).
Selects even children.
: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>
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;
}
Output
Select the first element of each type div and span.
:nth-of-type(1)

29

This website collects cookies to deliver better user experience

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