The difference between css selector nth-child and nth-of-type (you can’t learn to hit me)

The difference between css selector nth-child and nth-of-type (you can’t learn to hit me)

To distinguish between nth-child and nth-of-type, you only need to remember:
nth-child: first find the element according to the position, and then check whether the selector of the element conforms to
nth-of-type: first find all elements that match the selector, Classify them according to different tags, and then select the elements that match the position in each category


example

For the same html structure (as follows), we compare the two different selection methods of ul.son:nth-child(1) and ul.son:nth-type-of(1) , and analyze their selection:

<ul>
    <li class='son'>li.son</li>
    <p class='son'>p.son</p>
</ul>

The selector ul .son:nth-child(1) means: first find the first element under the ul tag, and then check whether the element satisfies .son

The li tag is eligible, but the p tag is not, because the p tag is not the first element under ul

<ul>
    <li class='son'>li.son</li> <!-- 选中 -->
    <p class='son'>p.son</p>    <!-- 未选中 -->
</ul>

The selector ul .son:nth-type-of(1) means: first find all elements under ul that satisfy .son, classify them according to different labels, and then select the first element in each category

Both li and p will be selected. It is worth noting that although the p tag is not the first element under ul, it ranks first among all p tags under ul, so it will also be selected (although it is not the first in the total score, it is the first in the subject)

<ul>
    <li class='son'>li.son</li> <!-- 选中 -->
    <p class='son'>p.son</p> <!-- 选中 -->
</ul>

Guess you like

Origin blog.csdn.net/m0_47659279/article/details/126530544