CSS表格交替行颜色和悬停颜色

时间:2016-03-21 16:03:52

标签: css html-table styling

我有一个包含类表的表。到目前为止唯一的造型是桌子。我想使用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;
}

到目前为止。寻找用于猜测表tr css的值。

说不同,因为偶数/奇数不起作用&amp;它的动态php不严格html。

2 个答案:

答案 0 :(得分:4)

你可以通过一点点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,我希望这就是你要找的。

答案 1 :(得分:4)

如果您已经将表格的背景颜色设置为白色,则只需设置备用行和悬停背景,如下所示:

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

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

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

此外,您可能不需要在每行FWIW上重复table课程。您可以像我一样使用.table tr来定位这些行。如果您正在尝试确保表格标题和正文样式不会相互干扰,那么将这些元素包含在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>

相关问题