我知道我可以通过指定id
轻松完成此操作,但我想练习伪选择器。
我在视图中有两个表。使用伪选择器:
<tbody>
中
<tr>
并将所有文字的颜色设为红色。我目前的实施几乎可行。问题在于它为视图中的每个表执行此样式设置。我希望这个样式在第一个表中只发生 。
tbody tr:first-child {
color: red;
}
&#13;
<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>
&#13;
答案 0 :(得分:5)
为表格使用另一个伪选择器:
table:nth-of-type(1) tbody tr:first-child {
color: red;
}
&#13;
<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>
&#13;
答案 1 :(得分:3)
您可以使用伪选择器更进一步,因为您已经知道自己定位了第一个表并使用:first-of-type
,其工作方式类似于:nth-of-type(1)
table:first-of-type 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>
答案 2 :(得分:0)
将表包装在容器元素中,然后应用此CSS
.container > :first-child tr:first-child td:last-child {
color: red;
}
<div class="container">
<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>
</div>
注意:这会将CSS应用于每个.container元素中的第一个表。只需指定一个ID,它应该不是问题