Home>Article>Web Front-end> Detailed explanation of CSS nth-child and nth-of-type element search methods
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
pgh1
pgh2
pgh3
pgh4
p1
p2
p3
p4
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:
pgh2
pgh3
pgh4
p2
p3
p4
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:
pgh1
pgh3
pgh4
p1
p3
p4
CSS unchanged:
##
p:nth-child(2) { color: red; font-weight:bold; } h5:nth-of-type(2) { color: blue; font-weight:bold; }Result: nth-child There is no effect, the nth-of-type highlighted is p3.
Why is this so?
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!