What is the difference between CSS3 pseudo class Nth-child and Nth-of-type?

Source: Internet
Author: User

First look at the similarities between Nth-child (n) and Nth-of-type (n)

The only common denominator between the two is: the use of parameter n

n can be numbers, keywords, or formulas (n > 0)

Nth-child (2) represents the second child element of its parent element

Nth-child (2n) or nth-child (even) represents the even number of child elements of its parent element

Nth-child (2n-1) or nth-child (odd) represents the first odd number of child elements of its parent element

And so on, other formulas about N.

Difference Analysis

About Nth-child
P:nth-child (2) {
Background: #ccc
}
The second child element of the parent element that acts on p, and if the element is not p, it is invalid

About Nth-of-type
P:nth-of-type (2) {
Background:red
}
The second P element (child element) of the parent element that acts on p

Examples of differences

HTML Code:
<p> first paragraph. </p>
<p> a second paragraph. </p>
<p> a third paragraph. </p>
<p> Fourth paragraph. </p>
<p> fifth paragraph. </p>
CSS Code
P:nth-child (2) {
Background: #ccc
}
P:nth-of-type (2) {
Background: #red;
}

Results diagram

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.