【问题标题】:CSS table alternate row colors and hover colors [duplicate]CSS表格交替行颜色和悬停颜色[重复]
【发布时间】:2016-07-08 06:08:25
【问题描述】:

我有一张带班级表的桌子。到目前为止,唯一的样式是表。我想使用 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。


说不同是因为偶数/奇数不起作用而且它是动态 php 而不是严格的 html。

【问题讨论】:

  • 请出示您目前拥有的代码

标签: css html-table styling


【解决方案1】:

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

.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>

【讨论】:

  • 忘记那部分了哈哈
【解决方案2】:

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

【讨论】:

  • 由于某些原因不起作用,我什至尝试了偶数/奇数设置。
  • 编辑:看到你更新的问题后,尝试给 tr 标签另一个类,它可能会发生,因为 tr 标签与 table 标签具有相同的类。我知道该表是用 php 生成的,但可能有一个选项可以重命名 tr 标签的类
猜你喜欢
  • 1970-01-01
  • 2017-07-07
  • 1970-01-01
  • 1970-01-01
  • 2014-02-05
  • 2011-08-15
  • 1970-01-01
  • 1970-01-01
  • 2015-03-08
相关资源
最近更新 更多