What is the difference between :Nth-Child and :Nth-of-type?

Asked

Viewed 861 times

4

Most of the time I use the :Nth-of-type but I didn’t understand exactly the difference between the two, someone can explain?

  • 2
  • @Bacco that would not be a more specific question?

  • 1

    The question is specific, but the answer given there answers with demonstration and everything. Remember that closure does not remove the question from the site and is not demerit, nor sign of problem. The question remains valid and serves as an index for the other post.

  • And the title of your question will help other users to find the solution, will be similar to merge :) ... its still linked :D

2 answers

8


the :nth-child() will consider all child elements "direct" value/past calculation between parentheses, so for example a "zebra effect":

div, p {
    background: #cfcfcf;
    margin: 2px 0;
}

p:nth-child(2n+1) {
    background: #f00;
}
<section>
    <p>a</p>
    <p>b</p>
    <p>c</p>

    <div>foo</div>

    <p>d</p>
    <p>e</p>
    <p>f</p>
</section>

<hr>

<section>
    <p>a</p>
    <p>b</p>
    <p>c</p>

    <div>foo</div>

    <p>d</p>
    <p>e</p>
    <p>f</p>
</section>

See that same <div>foo</div> being different from <p> still yes the zebra effect continues to consider it.

Now the effect is different with :nth-of-type, will notice that he will disregard the <div>foo</div>, because only those of the type defined before the : will be considered, result:

div, p {
    background: #cfcfcf;
    margin: 2px 0;
}

p:nth-of-type(2n+1) {
    background: #f00;
}
<section>
    <p>a</p>
    <p>b</p>
    <p>c</p>

    <div>foo</div>

    <p>d</p>
    <p>e</p>
    <p>f</p>
</section>

<hr>

<section>
    <p>a</p>
    <p>b</p>
    <p>c</p>

    <div>foo</div>

    <p>d</p>
    <p>e</p>
    <p>f</p>
</section>


See the difference of both in the image:

nth-child vs nth-of-type

At first (with nth-child) the <p>d</p> has the red background, because the previous element <div>foo</div> although not affected by CSS it is considered in the "calculus" 2n+1 (or whatever is passed between the parentheses).

Already in the second (with nth-of-type), the <p>d</p> continued gray and all that came after the <div>foo</div> has come to have other colors, because the <div>foo</div> is not considered as the selector nth-of-type specifies that they can only be of the same type for the calculation to consider.

0

The selector: Nth-Child, means to select an element if:

É um elemento de parágrafo.

É o segundo filho de um pai

The:Nth-of-type selector means to select an element if:

Selecione o segundo parágrafo filho de um pai

p:nth-child(2) { color: blue; }

p:nth-of-type(2) { color: red; }
<section>
   <p>Little</p>
   <span>Piggy</span>   
   <p>teste</p>
</section>

The Nth-of-type is less able to assess. source

Browser other questions tagged

You are not signed in. Login or sign up in order to post.