The difference between Nth-of-type and Nth-child

Source: Internet
Author: User

Look at CSS3 when found a nth-of-type selector, found that at ordinary times have not seen the use, on the study of a bit, the information is this:

: The Nth-of-type (n) selector matches each element of the nth child element of a particular type that belongs to the parent element.

Looks a lot like nth-child.

: The Nth-child (n) selector matches the nth child element that belongs to its parent element, regardless of the type of the element.

So what's the difference between the two? Test it.

Html:

        <Divclass= "box">Box:            <P>I'm P1.</P>              <P>I'm p2.</P>        </Div>        <Divclass= "pox">pox:            <P>I'm P1.</P>                    <P>I'm 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 result looks the same:

Here's a little bit of changing HTML:

         <Divclass= "box">Box:<Div>I'm div1.</Div>            <P>I'm P1.</P>            <Div>I'm div2.</Div>            <P>I'm p2.</P>        </Div>        <Divclass= "pox">pox:<Div>I'm the Div.</Div>            <P>I'm P1.</P>            <Div>I'm div2.</Div>            <P>I'm p2.</P>        </Div>        

Results:

It is found here that Nth-child does not work, which is why?

In fact P:nth-of-type (n) refers to the parent element under the nth P element, and P:nth-child (n) refers to the parent element under the nth element and this element is P, if not, the selection fails.

The first child element under Pox here is a div instead of p, so the selection fails. If you want to P1 red, P1 is pox under the second sub-element should choose Nth-child (2), should be replaced by:

. Pox P:nth-child (2) { color: red;}

Results:

The difference between Nth-of-type and nth-child

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.