📜 ⬆️ ⬇️

Differences between: nth-child and: nth-of-type

Suppose there is this HTML:
<section>
< p > Little < / p >
< p > Piggy < / p > <! - We need this element ->
< / section>

The following CSS will do the same thing:
p : nth- child ( 2 ) { color : red ; }

p : nth-of- type ( 2 ) { color : red ; }


Although, of course, in these selectors, there is a difference.

Pseudo-class : nth-child , means to select an element if:
  1. This element is a paragraph;
  2. This is the second element of one parent.

Pseudo-class : nth-of-type , means:
  1. Select the second paragraph of one parent.

Suppose our markup is changed as follows:
<section>
< h1 > Words < / h1 >
< p > Little < / p >
< p > Piggy < / p > <! - We need this element ->
< / section>

Now the first option does not work:
p : nth- child ( 2 ) { color : red ; } / * Does not work * /

The second continues to work:
p : nth-of- type ( 2 ) { color : red ; } / * Continues to work * /

By “Doesn't work,” I mean that the selector :nth-child chooses the word “Little” instead of “Piggy.” Because the element fulfills both conditions: 1) This is the second element of the parent element and 2) This is a paragraph. By "Continuing to work," I mean, the selector continues to be chosen "Piggy", because this is the second paragraph of the parent element.

If you add <h2> after <h1> , then the selector with: nth-child will not select anything , because the paragraph is no longer the second element. The c :nth-of-type selector will continue to work.
')
It seems to me :nth-of-type less fragile and more useful in general, despite this :nth-child continues to be the main work. How often do you think "I want to select the second element in the parent block if this is a paragraph." Maybe sometimes, but more often you think “Select the second paragraph” or “select every third row of the table”, for these tasks it is more suitable :nth-of-type (again, in my opinion).

Most of the situations when I say “Why does my selector with: nth-child not work?” Happen because I forget about selecting tags and the desired tag does not turn out to be the one that is needed. Therefore, when using :nth-child it is better to specify it from the parent and not use the tag binding.
dl : nth- child ( 2 ) { } / * This option is better than * /
dd : nth- child ( 2 ) { } / * this * /

But, of course, it all depends on the specific situation.

Browser support :nth-of-type pretty decent ... Firefox 3.5+, Opera 9.5+, Chrome 2+, Safari 3.1+, IE 9+. I would say if you need deeper support, then use jQuery (use the selector and use the class where necessary), but jQuery stopped supporting :nth-of-type . I heard that because of rare use, but it seems strange to me. If you want to go this way, then here is the plugin that returns support back .

Source: https://habr.com/ru/post/119139/


All Articles