在css或javascript中为表行和列设置备用颜色

时间:2016-11-21 07:43:02

标签: javascript css

我也试过使用下面的代码。它不适用于这种情况。

String Text

table>tbody>tr>td:nth-child(odd){
    background-color: #F2F2F2;
}
table>tbody>tr:nth-child(odd){
    background-color: #FFF !important;
}
table>tbody>tr>td:nth-child(even){
    background-color: #F7F7F7;
}

2 个答案:

答案 0 :(得分:3)

交替行

看到差异:我们在odd使用eventr,而不是td

table>tbody>tr:nth-child(odd) >td{
    background-color: #eee;
}
table>tbody>tr:nth-child(even)>td{
    background-color: #ccc;
}
<table>
  <tbody>
    <tr><td>. . . . .</td><td>. . . . .</td><td>. . . . .</td></tr>
    <tr><td>. . . . .</td><td>. . . . .</td><td>. . . . .</td></tr>
    <tr><td>. . . . .</td><td>. . . . .</td><td>. . . . .</td></tr> 
    <tr><td>. . . . .</td><td>. . . . .</td><td>. . . . .</td></tr>
    <tr><td>. . . . .</td><td>. . . . .</td><td>. . . . .</td></tr>
  </tbody>
</table>

似乎第一部分在这里得到了回答:
Alternate table row color using CSS?


交替的行和列:

如果您想要“加倍”替代,请将概念扩展到所有组合:

table>tbody>tr:nth-child(odd)> td:nth-child(odd) {background-color:#aaa}
table>tbody>tr:nth-child(odd)> td:nth-child(even){background-color:#888}
table>tbody>tr:nth-child(even)>td:nth-child(odd) {background-color:#eee}
table>tbody>tr:nth-child(even)>td:nth-child(even){background-color:#ddd}
<table>
  <tbody>
    <tr><td>. . . . .</td><td>. . . . .</td><td>. . . . .</td></tr>
    <tr><td>. . . . .</td><td>. . . . .</td><td>. . . . .</td></tr>
    <tr><td>. . . . .</td><td>. . . . .</td><td>. . . . .</td></tr> 
    <tr><td>. . . . .</td><td>. . . . .</td><td>. . . . .</td></tr>
    <tr><td>. . . . .</td><td>. . . . .</td><td>. . . . .</td></tr>
  </tbody>
</table>

答案 1 :(得分:0)

您的专栏css已覆盖了行css。因此,分别为oddeven行更改了它们,如下所示。

table>tbody>tr:nth-child(odd){
    background-color: #F7F7F7 !important;
}

table>tbody>tr:nth-child(even){
    background-color: #FFF !important;
}

table>tbody>tr:nth-child(odd)>td:nth-child(odd){
    background-color: #F2F2F2 !important;
}
table>tbody>tr:nth-child(odd)>td:nth-child(even){
    background-color: #F7F7F7;
}

table>tbody>tr:nth-child(even)>td:nth-child(odd){
    background-color: #FFF !important;
}
table>tbody>tr:nth-child(even)>td:nth-child(even){
    background-color: #F2F2F2;
}
<table>
  <tbody>
    <tr>
      <td>Row 1 Column 1</td>
      <td>Row 1 Column 2</td>
      <td>Row 1 Column 3</td>
    </tr>
    <tr>
      <td>Row 2 Column 1</td>
      <td>Row 2 Column 2</td>
      <td>Row 2 Column 3</td>
    </tr>
    <tr>
      <td>Row 3 Column 1</td>
      <td>Row 3 Column 2</td>
      <td>Row 3 Column 3</td>
    </tr>
    <tr>
      <td>Row 4 Column 1</td>
      <td>Row 4 Column 2</td>
      <td>Row 4 Column 3</td>
    </tr>
  </tbody>
</table>