首页 > 解决方案 > 在悬停时为 HTML 表格边框着色

问题描述

tr当我将鼠标悬停在它上面时,我想让它的顶部和底部边框改变颜色。我遇到的问题是tr上面的悬停样式覆盖了悬停样式(至少这是我认为正在发生的事情)。

在我的示例中,第一个项目正确悬停,但在第二个和第三个项目中,只有底部边框突出显示:

table {
  border-collapse: collapse;
}

th {
  background-color: rgb(231, 231, 231);
}

td {
  border-bottom: 2px solid rgb(214, 214, 214);
  border-top: 2px solid rgb(214, 214, 214);
}

table tr:hover td {
  border-bottom: 2px solid red;
  border-top: 2px solid red;
}
<table>
  <tr>
    <th>COMPANY</th>
    <th>CONTACT</th>
    <th>COUNTRY</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
</table>

标签: htmlcss

解决方案


如果你想保留你的 2 px 边框,你需要摆脱折叠,然后删除边框填充。然后,您可以使用同级选择器更改悬停时的正确边框。

在下面,我刚刚在您的表格中添加了一个 thead 和 tbody,以便我们知道只有 body 元素在悬停时会发生变化

table {
 border-spacing:0;
}

th {
  background-color: rgb(231, 231, 231);
}

td {
  border-top: 2px solid rgb(214, 214, 214); /* make all cells have a top border */
}

tbody tr:last-child td {
  border-bottom: 2px solid rgb(214, 214, 214);  /* make the last row also have a bottom border */ 
}

tbody tr:hover td {
  border-color: red;    /* change all borders to red on hover (mainly because of the last child bottom border */
}

tbody tr:hover + tr td {
  border-top-color: red;  /* change any cells without a bottom border - make the next row have top border go red (so it looks like current row bottom border) */
}
<table>
<thead>
  <tr>
    <th>COMPANY</th>
    <th>CONTACT</th>
    <th>COUNTRY</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
</tbody>
</table>


推荐阅读