tr:nth-child
does not select the expected row when the table it applies to has a caption.
When a section
has a h2
and several p
as children, p:nth-child(2)
selects the first p
after the h2
, which is what is expected. However, when using tr:nth-child(2)
on a table
with several rows and a caption
that naturally follows the opening table tag, the selector target the second tr
, as if the caption
did not exist.
tr:nth-child(2) {
background-color: red;
}
p:nth-child(2) {
background-color: red;
}
<table>
<caption>This caption is the table's first child</caption>
<tr>
<th>First row</th>
<td>1.2</td>
<td>1.3</td>
<td>1.4</td>
</tr>
<tr>
<th>Second row</th>
<td>2.2</td>
<td>2.3</td>
<td>2.4</td>
</tr>
<tr>
<th>Third row</th>
<td>3.2</td>
<td>3.3</td>
<td>3.4</td>
</tr>
</table>
<section>
<h1>Title (h1)</h1>
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>
</section>
I expect the tr:nth-child(2)
to select the first row since the 1st child of the table is the caption
.
The :nth-child() CSS pseudo-class matches elements based on their position among a group of siblings.
The :last-child selector allows you to target the last element directly inside its containing element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .
You can pass in a positive number as an argument to :nth-child() , which will select the one element whose index inside its parent matches the argument of :nth-child() . For example, li:nth-child(3) will select the list item with an index value 3; that is, it will select the third list item.
tr
elements cannot be child elements of a table
They must be child elements of a tbody
, thead
, or tfoot
element.
tbody
elements have optional start and end tags and are inserted implicitly if the author does not insert them explicitly.
The first tr
is the first child of the tbody
element, and is not a child of the table
element at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With