Is there a way to select the nth child element that matches (or does not match) any selector? For example, I want to select every odd table row, but in a subset of rows:
table.myClass tr.row:nth-child(odd) { ... }
<table class="myClass"> <tr> <td>Row <tr class="row"> <!-- I want this --> <td>Row <tr class="row"> <td>Row <tr class="row"> <!-- And this --> <td>Row </table>
But :nth-child()
seems to just count all tr
elements regardless of whether they are of class "row", so I end up with an even "row" element instead of the two elements I'm looking for. :nth-of-type()
The same thing happens.
Can anyone explain why?
P粉7878203962023-10-21 15:03:35
not real..
It is its own selector and is not combined with a class. In your rule, it only has to satisfy both selectors, so if the :nth-child(even)
table row also happens to have the .row代码> class.
P粉7648364482023-10-21 11:14:12
This is a very common question that arises due to a misunderstanding of how :nth-child(An B)
and :nth-of-type()
work.
In level 3 selectors, :nth-child ()
pseudo-class counts all sibling elements under the same parent. It doesn't just count siblings that match the rest of the selector.
Similarly, :nth-of-type()
Pseudo-class Counts sibling elements that share the same element type, which refers to the tag name in the HTML rather than the selector of the rest.
This also means that if all children of the same parent have the same element type, for example, the only child of the table body is the tr
element, or the only child of the list element is the child element is a li element, then :nth-child()
and :nth-of-type()
will behave the same, that is, for each value An B, :nth -child(An B)
and :nth-of-type(An B)
will match the same set of elements. p>
In fact, all simple selectors (including pseudo-classes such as :nth-child()
and :not()
) within a given compound selector will work Independently of each other, rather than looking at a subset of elements that match the rest of the selector.
This also means that there is no concept of order between the simple selectors within each individual compound selector 1, which means that for example the following two selectors are equivalent of: p>
table.myClass tr.row:nth-child(odd) table.myClass tr:nth-child(odd).row
Translated into English, they all mean:
(You'll notice I'm using an unordered list here, just to drive home the point)
Selector level 4 attempts to correct this limitation by allowing :nth-child(An B of S)
2 accepts any selector argument S, This is also due to how the selectors in a compound selector operate independently of each other, as determined by the existing selector syntax as shown below. So in your case it would look like this:
table.myClass tr:nth-child(odd of .row)