Difference between nth-of-type and nth-child, nth-of-type
When I checked out CSS3, I found an nth-of-type selector. I found that I have never seen it before. So I studied it. w3c explained it as follows:
: Nth-of-type (N) The selector matches each element of the nth child element of a specific type of the parent element.
It looks like nth-child.
: Nth-child (N) The selector matches the nth child element of the parent element, regardless of the element type.
So what is the difference between the two? Test it.
HTML:
<Div class = "box"> box: <p> I am p1 </p> <p> I am p2 </p> </div> <div class = "pox"> pox: <p> I am p1 </p> <p> I am p2 </p> </div>
CSS:
<style> .box{ margin: 100px; float: left; } .pox{ margin: 100px 0 0 60px; float: left; } .pox p:nth-child(1){ color: red; } .box p:nth-of-type(1){ color: red; } </style>
The results are similar:
Here we will slightly change the HTML:
<Div class = "box"> box: <div> I am div1 </div> <p> I am p1 </p> <div> I am div2 </div> <p> I am p2 </p> </div> <div class = "pox"> pox: <div> I am div </div> <p> I am p1 </p> <div> I am div2 </div> <p> I am p2 </p> </div>
Result:
Here we find that nth-child does not work. Why?
In fact, p: nth-of-type (n) refers to the nth p element under the parent element, while p: nth-child (n) it refers to the nth element under the parent element and the element is p. If not, the selection fails.
The first child element in pox is div rather than p, so the selection fails. If you want p1 to become red, p1 is the second child element in pox. You should select nth-child (2) and change it:
.pox p:nth-child(2){ color: red; }
Result: