Selects one or more child elements of the parent element.
Argument “n” can be any one of the following three ways.
1. “n” can be a number.
Selects specified element when it is available in “n”th index order.
|
Selects 2nd index order P child element of the parent element. Parent element could be any one of the valid HTML element. Question: What will happen when 2nd index order element is not a P element? Ans: That element will not be selected for styling. |
Example :
Result:
In the above example,
|
2. “n” can be a keyword (odd/even).
Selects all odd/even child elements of the parent when specified element is available on odd/even index order.
|
Selects all even (2, 4, 6, 8, etc.,) index P child elements of the parent.
Question: What will happen when one or more even index order elements are not P elements. Ans: Those elements will not be selected for styling. |
Example :
Result:
In the above example,
|
3. “n” can be a formula (an + b).
1 | “a” and “b” are integer values. “n” value is implicitly iterated from 0. |
2 |
In the example ( p:nth-child(3n+2) ), elements are selected in the following way, 3*0 + 2 = 2nd element. 3*1 + 2 = 5th element. 3*2 + 2 = 8th element and continues until end. “n” value starts from 0. |
3 |
In the formula (an + b), if 1. “a” and “b” values are greater than 0 and 2. “a” value is greater than or equal to “b” value (ex., 3n+2) then Elements are divided into group of “a”(number) elements and selects every “b” index order specified element from each group. |
Example : Pseudo class (:nth-child) with different types of arguments.
<!DOCTYPE html>
<html>
<head>
<title> CSS pseudo-class selector - :nth-child</title>
<style>
div {
width:10%;
float:left;
}
.clsNth p:nth-child(2) {
background-color:red;
}
.clsKeyWord p:nth-child(even) {
background-color:green;
color:white;
}
.clsFormula p:nth-child(3n + 2) {
background-color:yellow;
}
.clsFormula2 p:nth-child(2n + 3) { /* a < b */
background-color:yellow;
}
</style>
</head>
<body>
<div class="clsNth">
<p> One</p>
<p> Two </p>
<p> Three </p>
<p> Four </p>
<p> Five </p>
<p>Six </p>
<p> Seven </p>
<p> Eight </p>
<p> Nine </p>
<p> Ten </p>
</div>
<div class="clsKeyWord">
<p> One</p>
<p> Two </p>
<p> Three </p>
<p> Four </p>
<p> Five </p>
<p>Six </p>
<p> Seven </p>
<p> Eight </p>
<p> Nine </p>
<p> Ten </p>
</div>
<div class="clsFormula">
<p> One</p>
<p> Two </p>
<p> Three </p>
<p> Four </p>
<p> Five </p>
<p>Six </p>
<p> Seven </p>
<p> Eight </p>
<p> Nine </p>
<p> Ten </p>
</div>
<div class="clsFormula2">
<p> One</p>
<p> Two </p>
<p> Three </p>
<p> Four </p>
<p> Five </p>
<p>Six </p>
<p> Seven </p>
<p> Eight </p>
<p> Nine </p>
<p> Ten </p>
</div>
</body>
</html>
Result:
In the above example,