如何在每行和每列中替换表格单元格背景颜色

时间:2016-12-28 11:01:43

标签: css

我想格式化CSS,如图所示:在奇数行中,第一列单元格和偶数行中第二列单元格应使用不同的背景颜色进行格式化。

example table

我知道如何替换

之类的整行或列
tr {
border-top: 0px solid $input-border-col;
&:first-child {
    border-top: none;
}
&:nth-child(even) {background: #CCC;}
}

但尚未找到如何在每一行中交替的方法

4 个答案:

答案 0 :(得分:5)

您可以使用oddeven CSS伪名称。

与此类似,您的<tr>会有多少<td><table>

td {
  padding: 20px;
  border: 1px solid black;
}

table tr:nth-child(odd) td:nth-child(odd),
table tr:nth-child(even) td:nth-child(even) {
    background: orange;
}
<table>
  <tr>
    <td>x</td>
    <td>x</td>
    <td>x</td>
    <td>x</td>
  </tr>
  <tr>
    <td>x</td>
    <td>x</td>
    <td>x</td>
    <td>x</td>
  </tr>
  <tr>
    <td>x</td>
    <td>x</td>
    <td>x</td>
    <td>x</td>
  </tr>
  <tr>
    <td>x</td>
    <td>x</td>
    <td>x</td>
    <td>x</td>
  </tr>
</table>

答案 1 :(得分:3)

您可以将nth-child选择器与first/last child结合使用,以获得所需的结果。因此,您可以选择所有tr 2n + 1或奇数行,然后选择第一个td,然后选择tr 2n + 2甚至行,并选择最后{{1} }}

&#13;
&#13;
td
&#13;
td {
  padding: 20px;
  border: 1px solid black;
}

tr:nth-child(2n + 1) td:first-child,
tr:nth-child(2n + 2) td:last-child {
  background: #EA9999;
}
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您可以使用以下规则:

tr {
    &:nth-child(odd) {
        >td {
            &:nth-child(odd) {
                background-color: red;
            }
            &:nth-child(even) {
                background-color: white;
            }
        }
    }
    &:nth-child(even) {
        >td {
            &:nth-child(odd) {
                background-color: white;
            }
            &:nth-child(even) {
                background-color: red;
            }
        }
    }
}

答案 3 :(得分:1)

以下是此

的解决方案
table{ width:100%}
    td {
      padding: 20px;
      border: 1px solid black;
    }

    tr:nth-child(2n + 1) td:first-child,
    tr:nth-child(2n + 2) td:last-child {
      background: #EA9999;
    }
    <table>
      <tr>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
      </tr>
    </table>
相关问题