What is the difference between the: nth-child and the: nth-of-type?

4

Most of the time I use : nth-of-type but I did not quite understand the difference between the two, can anyone explain?

    
asked by anonymous 12.04.2018 / 19:47

2 answers

7

:nth-child() will consider all direct child elements in the value / calculation passed between parentheses, then 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 even <div>foo</div> being different from <p> yet the zebra effect still considers it.

Now the effect is different with :nth-of-type , you will notice that it will disregard <div>foo</div> , since only those of type defined before : 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:

In the first one (with nth-child ) the <p>d</p> was left with the red background, because the previous element <div>foo</div> although not affected by the CSS it is considered in the calculation 2n+1 (or any be passed between parentheses).

In the second one (with nth-of-type ), <p>d</p> remained gray and everything that came after <div>foo</div> has other colors, because <div>foo</div> is not considered since the nth-of-type specifies that they can only be of the same type for the calculation to consider.

    
12.04.2018 / 20:06
0
  

The selector: nth-child, means to select an element if:

É um elemento de parágrafo.

É o segundo filho de um pai

  

The selector: nth-of-type, 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>
  

nth-of-type has less evaluation conditions. font

    
12.04.2018 / 20:12