CSS table 交替行颜色和悬停颜色

CSS table alternate row colors and hover colors

我有一个 table 和 class table。到目前为止唯一的样式是第 table 次。我想使用 CSS 值在行的白色和银色之间交替,并为整行悬停银色。有人有代码吗?


<table class='table'>
  <tr>
   <th>heading</th>
   <th>heading 2</th>
   <th>heading 3</th>
  </tr>
  <tr class='table'>
    <td>col 1</td>
    <td>col 2</td>
    <td>col 3</td>
  </tr>
  <tr class='table'>
    <td>col 1</td>
    <td>col 2</td>
    <td>col 3</td>
  </tr>
  <tr class='table'>
    <td>col 1</td>
    <td>col 2</td>
    <td>col 3</td>
  </tr>
</table>

这就是 html 示例(如 php 中所写)

CSS

.table {
background-color: #FFFFFF;
color: #000000;
}

.table th {
background-color: #333333;
color: #FFFFFF;
}

到此为止。寻找用于我猜测 table tr css.

的值

说的不一样,因为 even/odd 不起作用,它是动态的 php 不严格 html。

你可以通过一点点实现css,只需使用第 n 个子选择器,就像这样:

HTML:

<table class="alternate">
<tr>
  <td>Row Col 1 </td>
  <td>Row Col 2 </td>
</tr>
<tr>
  <td>Row Col 1 </td>
  <td>Row Col 2 </td>
</tr>
<tr>
  <td>Row Col 1 </td>
  <td>Row Col 2 </td>
</tr>
<tr>
  <td>Row Col 1 </td>
  <td>Row Col 2 </td>
</tr>
</table>

CSS:

.alternate tr:nth-child(2n) {
  background-color: silver;
}

.alternate tr {
  background-color: white;
}

.alternate tr:nth-child(2n):hover, .alternate tr:hover {
  background-color: grey;
}

这是一个有效的 fiddle,我希望这就是您要找的。

如果您已经将 table 的背景颜色设置为白色,则只需设置交替行和悬停背景,如下所示:

.table tr {
    transition: background 0.2s ease-in;
}

.table tr:nth-child(odd) {
    background: silver;
}

.table tr:hover {
    background: silver;
    cursor: pointer;
}

此外,您可能不需要在每一行上重复 table class,FWIW。您可以像我一样使用 .table tr 定位这些行。如果你想确保 table header 和 body 样式不会相互干扰,那么将这些元素包装在 theadtbody:

<table class='table'>
  <thead>
    <tr>
      <th>heading</th>
      <th>heading 2</th>
      <th>heading 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>col 1</td>
      <td>col 2</td>
      <td>col 3</td>
    </tr>
    <tr>
      <td>col 1</td>
      <td>col 2</td>
      <td>col 3</td>
    </tr>
    <tr>
      <td>col 1</td>
      <td>col 2</td>
      <td>col 3</td>
    </tr>
  </tbody>
</table>