Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
775 views
in Technique[技术] by (71.8m points)

css - What is the difference between p:nth-child(2) and p:nth-of-type(2)?

What is the difference between p:nth-child(2) and p:nth-of-type(2)?

As per W3Schools CSS Selector Reference:

  • p:nth-child(2): Selects every <p> element that is the second child of its parent.
  • p:nth-of-type(2): Selects every <p> element that is the second <p> element of its parent.

The difference seem to be child of its parent and <p> element of its parent.

If we are already mentioning the element type as <p> in both the cases and the keyword parent establishes a parent-child relation, so what can be the difference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For p:nth-child(2) it selects the second element of its parent element if it's a paragraph whereas p:nth-of-type(2) will select the second paragraph of its parent element. If you are still confused let's make me clarify it for you. Consider the code snippet below:

<section>
   <h1>Words</h1>
   <p>Little</p>
   <p>Piggy</p>    <!-- Want this one -->
</section>

Here, p:nth-child(2) will select <p>Little</p> because it is the second child of its parent and it a paragraph element.

But, Here, p:nth-of-type(2) will select <p>Piggy</p> because it will select the second paragraph among all the paragraph of its parent.

Help from: https://css-tricks.com/the-difference-between-nth-child-and-nth-of-type/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...