我知道我可以通过指定 id
轻松做到这一点但我想练习伪选择器。
我在一个 View 中有两个表。使用伪选择器:
- 我只想抢第一张 table 。
- 在第一个表的
<tbody>
中- 我想抢第一个
<tr>
并将所有文本涂成红色。
- 我想抢第一个
- 在第一个表的
我目前的实现几乎可以正常工作。问题是它对 View 中的每个 表都进行了这种样式设置。我希望这种样式只出现在第一个表中。
tbody tr:first-child {
color: red;
}
<table>
<thead>
<tr>
<th>First Column</th>
<th>Second Column</th>
</tr>
</thead>
<tbody>
<tr>
<td> T1 R1 Col 1</td>
<td>This row should all be red</td>
</tr>
<tr>
<td>T1 R2 Col 1</td>
<td>foobar</td>
</tr>
</tbody>
</table>
<br>
<table>
<thead>
<tr>
<th>First Column</th>
<th>Second Column</th>
</tr>
</thead>
<tbody>
<tr>
<td> T2 R1 Col 1</td>
<td>This row should NOT be red</td>
</tr>
<tr>
<td>T2 R2 Col 1</td>
<td>foobar</td>
</tr>
</tbody>
</table>
最佳答案
为表格使用另一个伪选择器:
table:nth-of-type(1) tbody tr:first-child {
color: red;
}
<table>
<thead>
<tr>
<th>First Column</th>
<th>Second Column</th>
</tr>
</thead>
<tbody>
<tr>
<td> T1 R1 Col 1</td>
<td>This row should all be red</td>
</tr>
<tr>
<td>T1 R2 Col 1</td>
<td>foobar</td>
</tr>
</tbody>
</table>
<br>
<table>
<thead>
<tr>
<th>First Column</th>
<th>Second Column</th>
</tr>
</thead>
<tbody>
<tr>
<td> T2 R1 Col 1</td>
<td>This row should NOT be red</td>
</tr>
<tr>
<td>T2 R2 Col 1</td>
<td>foobar</td>
</tr>
</tbody>
</table>
关于使用 first-child 的 CSS 伪选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39083397/