I can not understand the difference between nth-child and nth-of-type in css?
For example, I use:
.container .elem:nth-child(1) { property: value } But this does not always work for the first or nth element.
What could be the problem?
I can not understand the difference between nth-child and nth-of-type in css?
For example, I use:
.container .elem:nth-child(1) { property: value } But this does not always work for the first or nth element.
What could be the problem?
p:nth-child(2) will work for the second element (sampling occurs among all elements, regardless of type; no matter p , li or a ), which is p if the second element in nesting is not p then it will not work.
p:nth-of-type(2) will work for, namely, the second p , if there is such an element at all or the number of such elements is greater than or equal to 2.
If you have in the nested block elements of the same type, then you will not see the difference between the two given pseudo-classes.
div p:nth-child(2) { background-color: #66ff66; } div p { border: 1px solid black; } <div> <p>Первый параграф</p> <p>Второй параграф</p> <!-- Нужен этот элемент --> </div> div p:nth-of-type(2) { background-color: #66ff66; } div p { border: 1px solid black; } <div> <p>Первый параграф</p> <p>Второй параграф</p> <!-- Нужен этот элемент --> </div> If you add, say, a heading to the beginning, then p:nth-child(2) will work for the first paragraph (the second element in order, which corresponds to the type p ).
In the case of p:nth-of-type(2) choice will occur only among the elements of p , and the second in a row, p , is what we need.
div p:nth-child(2) { background-color: #66ff66; } div p { border: 1px solid black; } <div> <h1>Первый заголовок</h1> <p>Первый параграф</p> <p>Второй параграф</p> <!-- Нужен этот элемент --> </div> div p:nth-of-type(2) { background-color: #66ff66; } div p { border: 1px solid black; } <div> <h1>Первый заголовок</h1> <p>Первый параграф</p> <p>Второй параграф</p> <!-- Нужен этот элемент --> </div> Absolutely the same principle works for first-child and first-of-type , if we assume that first-child is equal to nth-child(1) and first-of-type is equal to nth-of-type(1) .
I think the explanation is quite clear, if you have questions, I can add an answer.
Source: https://ru.stackoverflow.com/questions/853095/
All Articles