<section>
< p > Little < / p >
< p > Piggy < / p > <! - We need this element ->
< / section>
p : nth- child ( 2 ) { color : red ; }
p : nth-of- type ( 2 ) { color : red ; }
<section>
< h1 > Words < / h1 >
< p > Little < / p >
< p > Piggy < / p > <! - We need this element ->
< / section>
p : nth- child ( 2 ) { color : red ; } / * Does not work * /
p : nth-of- type ( 2 ) { color : red ; } / * Continues to work * /
: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.<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.: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).: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 * /
: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