CSS for tr in table

CSS for tr in table

本文关键字:table in tr for CSS      更新时间:2023-09-26

是否可以将背景颜色更改为表中的特定tr ?我怎样才能使从id=1到id=2的每个tr都是蓝色的,id=2到id=3的每个tr都是红色的等等。

我有这样的代码:

<tbody>
<tr id="1"></tr>   <-- Blue
<tr></tr>          <-- Blue
<tr></tr>          <-- Blue
<tr id="2"></tr>   <-- Red
<tr></tr>          <-- Red
<tr id="3"></tr>   <-- Green
<tr></tr>          <-- Green
<tr></tr>          <-- Green
<tr></tr>          <-- Green
</tbody>

试试这个:

[id="1"], [id="1"] ~ tr {
  background-color: blue;
}
[id="2"], [id="2"] ~ tr {
  background-color: red;
}
[id="3"], [id="3"] ~ tr {
  background-color: green;
}
<table>
<tbody>
<tr id="1"><td>foo</td></tr>
<tr><td>foo</td></tr>
<tr><td>foo</td></tr>
<tr id="2"><td>foo</td></tr>
<tr><td>foo</td></tr>
<tr id="3"><td>foo</td></tr>
<tr><td>foo</td></tr>
<tr><td>foo</td></tr>
<tr><td>foo</td></tr>
</tbody>
</table>

查找CSS n -childhttp://www.w3schools.com/cssref/sel_nth-child.asp

例如:

tr:nth-child(5n+3) {background-color:red}

或者Css类选择器也可以选择

.blue{
background-color:blue;
color:white
}
.red{
background-color:red;
color:white
}
.green{
background-color:green;
color:white
}
<table>
<tbody>
<tr id="1" class="blue"><td>blue</td></tr>   
<tr  class="blue"><td>blue</td></tr>         
<tr  class="blue"><td>blue</td></tr>   
<tr id="2" class="red"><td>red</td></tr>   
<tr  class="red"><td>red</td></tr>         
<tr id="3" class="green"><td>green</td></tr>   
<tr  class="green"><td>green</td></tr>         
<tr  class="green"><td>green</td></tr>  
<tr  class="green"><td>green</td></tr>         
<tr  class="green"><td>green</td></tr>  
</tbody>
</table>