First look at the similarities between Nth-child (n) and Nth-of-type (n)
The only common denominator between the two is: the use of parameter n
n can be numbers, keywords, or formulas (n > 0)
Nth-child (2) represents the second child element of its parent element
Nth-child (2n) or nth-child (even) represents the even number of child elements of its parent element
Nth-child (2n-1) or nth-child (odd) represents the first odd number of child elements of its parent element
And so on, other formulas about N.
Difference Analysis
About Nth-child
P:nth-child (2) {
Background: #ccc
}
The second child element of the parent element that acts on p, and if the element is not p, it is invalid
About Nth-of-type
P:nth-of-type (2) {
Background:red
}
The second P element (child element) of the parent element that acts on p
Examples of differences
HTML Code:
<p> first paragraph. </p>
<p> a second paragraph. </p>
<p> a third paragraph. </p>
<p> Fourth paragraph. </p>
<p> fifth paragraph. </p>
CSS Code
P:nth-child (2) {
Background: #ccc
}
P:nth-of-type (2) {
Background: #red;
}
Results diagram