: Nth-child and: Nth-of-type are CSS3 in the pseudo-class selector, its role is similar but not exactly the same, for unfamiliar people may not be very different, this article will introduce the difference between the two, in order to facilitate the correct use of both types of selectors.
Let's look at the following two lines of CSS:
P:nth-child (2) {color:red;}
P:nth-of-type (2) {color:red;}
① for :nth-child
selectors, to put it simply, selecting an element satisfies the following requirements:
- This is a paragraph p tag element
- The element is the second child element of the parent tag
② for :nth-of-type
selectors means selecting an element to satisfy:
- This is a paragraph p tag element
- The label is the second paragraph P element in the parent element, only the P tag in the parent element, and the other labels do not count
Again for example:
<section> <div> I am a normal div tag </div> <p> I am the 1th p tag </p> <p> I am the 2nd p tag </p> <!--want this to turn red--></section>
or the CSS test code that is consistent with the example above:
P:nth-child (2) {color:red;}
P:nth-of-type (2) {color:red;}
At this time two selectors render the results such as:
P:nth-child (2) {color:red;} The Display effect
P:nth-of-type (2) {color:red;} The Display effect
Comparing the semantics of the above two selectors, the difference in performance here is not difficult to understand.
For p:nth-child(2)
this element to be a p
label, and the second child element, two conditions must be met. So, the first p
label color is red (just match: P tag, second child element).
Instead p:nth-of-type(2)
of representing the second element under the parent tag p
, it is clear that the div
span
h1
text in the second label is red, whether you insert a label or a label after the label p
.
The difference between the two is a realistic analogy with family planning: The former is a second child and a girl, fine! The latter is the tube of his first few births, the second born girl, fine!
CSS3 selector: Nth-child and: Differences between Nth-of-type