这是我当前的表格:
<table>
<tr>
<td>a</td>
</tr>
<tr>
<td>b</td>
</tr>
<tr>
<td>c</td>
</tr>
<tr>
<td>d</td>|
</tr>
</table>
现在,我希望前两行具有红色背景色,接下来的两行具有蓝色。
答案 0 :(得分:2)
nth-child
允许您使用元素出现的顺序来定位每个元素。像前两个元素这样的特殊选择需要nth-child(-n+2)
,而后两个元素需要nth-last-child(-n+2)
tr:nth-child(1),
tr:nth-child(2) {
background: red;
}
tr:nth-child(3),
tr:nth-child(4) {
background: blue;
}
<table>
<tr>
<td>a</td>
</tr>
<tr>
<td>b</td>
</tr>
<tr>
<td>c</td>
</tr>
<tr>
<td>d</td>
</tr>
</table>
tr:nth-child(-n+2) {
background: red;
}
tr:nth-last-child(-n+2) {
background: blue;
}
<table>
<tr>
<td>a</td>
</tr>
<tr>
<td>b</td>
</tr>
<tr>
<td>c</td>
</tr>
<tr>
<td>d</td>
</tr>
</table>
答案 1 :(得分:1)
前两行: css:
table tr:not(:nth-child(n+3)) {
background: red;
}
,并持续: css:
table tr:nth-child(n+3) {
background: blue;
}