HTML表格中有rowspan时颜色第一列

时间:2014-11-08 10:22:38

标签: html css

以下是一个简单的小表作为例子。我希望标题行为一种颜色(灰色)。标题下方的备用行为另一种颜色(黄色)。而另一种颜色的第一列(橙色)。 我无法通过CSS实现所需的结果。如何在不单独着色细胞的情况下进行操作。

JSFiddle

中的代码

table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
  text-align: center;
  padding: 5px;
}
table {
  width: 100%;
}
th {
  background-color: grey;
  color: white;
}
tr:nth-child(odd) {
  background-color: yellow;
}
<table>
  <col style="background-color: orange;" />

  <tr>
    <th>&nbsp;</th>
    <th>Bank</th>
    <th>Amount</th>
  </tr>
  <tr>
    <td>John</td>
    <td>ABC</td>
    <td>12345</td>
  </tr>
  <tr>
    <td rowspan="2">David</td>
    <td>DEF</td>
    <td>456789</td>
  </tr>
  <tr>
    <td>GHI</td>
    <td>147258</td>
  </tr>
  <tr>
    <td>Kevin</td>
    <td>JKL</td>
    <td>258369</td>
  </tr>
  <tr>
    <td>Mike</td>
    <td>MNO</td>
    <td>369258</td>
  </tr>
</table>

2 个答案:

答案 0 :(得分:4)

这不是一个很好的解决方案,但这是一个修复: http://jsfiddle.net/sthmw0dk/2/

我添加了以下几行:

tr td:first-child
{
    background-color: orange;
}
tr:nth-child(even) td:nth-last-child(2)
{
    background-color: white;
}
tr:nth-child(odd) td:nth-last-child(2)
{
    background-color: yellow;
}

将行数更改为3或更多时,最后一个选择器是必需的。

但我会建议您使用第一列的课程。如果您希望将来使用更多列,那将会更容易。

答案 1 :(得分:0)

演示 - http://jsfiddle.net/victor_007/sthmw0dk/3/

我唯一改变的是造型td而不是tr <{1}}

使用background-color tr的td:not(:first-child)将无法获得任何样式

first-child
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
  text-align: center;
  padding: 5px;
}
table {
  width: 100%;
}
th {
  background-color: grey;
  color: white;
}
.first-col {
  background-color: orange;
}
tr:nth-child(odd) td:not(:first-child) {
  background-color: yellow;
}

相关问题