For beginners, the difference between “nTH-child” and “nTH-of-type” is a headache problem, in order to better help you distinguish the two use methods, especially to distinguish here.

Start by creating an HTML structure.

< div class = “post” > < p > I was the first paragraph of the article < / p > < p > I of the article the second paragraph < / p >

Next, use “: nth-Child” and “:nth-of-type” to select the paragraph and change its text color.

.post>p:nth-child(2){color:red; } .post>p:nth-of-type(2){color:red; }

The code above makes the second text in “POST” bright red. Does this mean that the two selectors are the same? It’s not. Nth-child means two things, just literally. The first is a paragraph element that is the second child of the parent element “div”; Nth-of-type literally means “select paragraph 2 of parent div”.

Does the above paragraph look confusing? Is there a better way to tell them apart? ~ ~ ~ some! Change the HTML structure above by adding a heading “H1” before the paragraph.

< h1 > I am a title < / h1 > < p > I was the first paragraph of the article < / p > < p > I of the article the second paragraph < / p >

The style is the same, but the structure is completely different. “P: nth-Child (2)” does not select paragraph 2, but paragraph 1, thus not achieving the desired effect.

.post>p:nth-child(2){color:red; }/* The first paragraph turns red, which is not what we want */

“Nth-child (2)” is the wrong paragraph, but “p:nth-of-type(2)” works.

.post>p:nth-of-type(2){color:red; }/* The second paragraph turns red, which is what we want */

If you add a “h2” heading after the “h1” heading, “p: nth-Child (2)” will not be able to select any element, because the second element of the “div” is not paragraph 1 “P”, so no element can be selected. But “p:nth-of-type(2)” still works because the second paragraph “p” in “div” is always selected.

The only thing to remember is that nth-child selects a child of the parent element. This child does not specify an exact type, and is valid only if two conditions are met: one is the child element, and the other is the child element in that position; Nth-of-type selects a child of a parent element of the specified type.