Difference between nth-of-type and nth-child, nth-of-type

Source: Internet
Author: User

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:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.