nth-child and nth-of-type are two pseudo-selectors of CSS. In applications, the two are often confused. Let’s take them out and compare them carefully to see how they find elements. This article mainly introduces relevant information that explains in detail the element search methods of CSS nth-child and nth-of-type. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
nth-child(n) —— Find the nth child element
nth-of-type(n) —— Find the same type The nth element in the element
may not be very clear about their differences based on this definition. Let’s distinguish them bit by bit.
p:nth-child(2) and p:nth-pf-type(2)
HTML code is as follows
<p> <p style="float:left;width:200px;"> <p>pgh1</p> <p>pgh2</p> <p>pgh3</p> <p>pgh4</p> </p> <p style="float:left;width:200px;"> <h5>p1</h5> <h5>p2</h5> <h5>p3</h5> <h5>p4</h5> </p>
Apply two styles respectively, both looking for the second element
p:nth-child(2) { color: red; font-weight:bold; } h5:nth-of-type(2) { color: blue; font-weight:bold; }
Result: Both are applied successfully.
Now let’s make some changes to the HTML code to make them look different. We changed the first p element and the first h5 element to label. The code is as follows:
<p> <p style="float:left;width:200px;"> <label>pgh1</label> <p>pgh2</p> <p>pgh3</p> <p>pgh4</p> </p> <p style="float:left;width:200px;"> <label>p1</label> <h5>p2</h5> <h5>p3</h5> <h5>p4</h5> </p>
The style remains unchanged. Now look at the effect and find that nth-of The result of -type(2) has changed, and p3 is highlighted now. This is considered consistent with our logic. h5:nth-of-type(2) is looking for the second element of type h5, which is p3.
Continue to change the HTML code. We restore the first p element and the first h5 element, and change the second p element and the second h5 element to label. The style remains unchanged. What will be the result?
HTML is as follows:
<p> <p style="float:left;width:200px;"> <p>pgh1</p> <label>pgh2</label> <p>pgh3</p> <p>pgh4</p> </p> <p style="float:left;width:200px;"> <h5>p1</h5> <label>p2</label> <h5>p3</h5> <h5>p4</h5> </p>
CSS unchanged:
##
p:nth-child(2) { color: red; font-weight:bold; } h5:nth-of-type(2) { color: blue; font-weight:bold; }
Why is this so?
pgh3
is the second-ranked element in the p type; in the p on the right,pgh3
on the left p will not.Analysis of techniques to improve the efficiency of element search and element deduplication in PHP arrays, php array_PHP tutorial
A brief analysis of the summary of commonly used element search methods in jQuery_jquery
Detailed explanation of the difference between nth-child and nth-of-type in CSS3
The above is the detailed content of Detailed explanation of CSS nth-child and nth-of-type element search methods. For more information, please follow other related articles on the PHP Chinese website!