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

标签 css html-table styling

<分区>

我有一张带有类表的表。到目前为止唯一的样式是 table th。我想使用 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。

最佳答案

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

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

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

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

此外,您可能不需要在每一行上重复 table 类,FWIW。您可以像我一样使用 .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>

关于CSS 表格交替行颜色和悬停颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36136019/

相关文章:

html - 如何将div背景置于其内容之上

html - Rowspan 不使用顶行

html - 为什么我的列最大宽度为 282 像素而不是 660 像素?

twitter-bootstrap-3 - 将 Bootstrap 具有错误样式应用于 select2 元素

javascript - 当我提交带有编辑和删除按钮的表单时显示所有值

html - p :layoutUnit ignore the margin-top

javascript - div 上的交替背景颜色

php - Bootstrap 4表格td宽度尺寸自定义

reactjs - 在没有主题的情况下 react KeyboardDatePicker 样式

Android 开发 - 在哪里可以找到 "original"晦涩的组件文档