Home  >  Article  >  Web Front-end  >  Compare the differences between CSS3 selectors :nth-child and :nth-of-type

Compare the differences between CSS3 selectors :nth-child and :nth-of-type

巴扎黑
巴扎黑Original
2017-09-20 09:51:591858browse

This article mainly introduces the difference between CSS3 selectors: nth-child and :nth-of-type. It is of great practical value. Friends in need can refer to it.

Let’s look at a simple one first. Example, first the HTML part:


<section>
    <p>我是第1个p标签</p>
    <p>我是第2个p标签</p>  <!-- 希望这个变红 -->
</section>

Then the CSS code corresponding to the two selectors is as follows:


p:nth-child(2) { color: red; }


p:nth-of-type(2) { color: red; }

In the above example, the effects achieved by these two selectors are consistent, and the text of the second p tag turns red:

Although the final effects of the above two demos are the same, differences between the two selectors are inevitable.

For the :nth-child selector, in simple vernacular, it means selecting an element:

1. This is a paragraph element
2. This is The second child element of the parent tag

For the :nth-of-type selector, it means selecting an element:

1. Select the second child element of the parent tag Paragraph sub-element

If we slightly modify the above example, we can see the difference between the two selectors, as shown in the following HTML code:


<section>
    <p>我是一个普通的p标签</p>
    <p>我是第1个p标签</p>
    <p>我是第2个p标签</p>  <!-- 希望这个变红 -->
</section>

Still the same CSS test code as the above example:


p:nth-child(2) { color: red; }


p:nth-of-type(2) { color: red; }

At this time, the results rendered by the two selectors are different.

p:nth-child(2) The rendering result is not that the text of the second p tag turns red, but the first p tag, which is the second child element of the parent tag.

The performance of p:nth-of-type(2) is very strong, it dyes the second p tag that you want to render red.

The above is the detailed content of Compare the differences between CSS3 selectors :nth-child and :nth-of-type. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn