You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为tr hover时的border-spacing间距设置背景颜色?

解决表格行间距hover背景色无法覆盖的问题

问题原因

border-spacing 产生的行间距属于表格容器的空白区域,并不属于 <tr> 元素的范围,所以 <tr:hover> 的背景色只能覆盖 <tr> 本身,无法填充这些间距区域。

解决方案

下面提供两种可行的替代方案:

方案一:用伪元素模拟行间距

放弃 border-spacing,通过给 <tr> 添加伪元素来模拟行间距,这样hover时可以同时控制伪元素的背景色:

table {
  border-collapse: collapse;
  width: 100%;
}
/* 给除第一行之外的所有行上方添加伪元素作为间距 */
tr:not(:first-child):before {
  content: "";
  display: table-row;
  height: 5px;
  background-color: #ffffff; /* 默认和表格背景色一致 */
}
/* hover时同时改变行和伪元素的背景色 */
tr:hover,
tr:hover:before {
  background-color: red;
}

方案二:利用透明边框替代行间距

通过给 <tr> 设置透明上下边框,把间距纳入 <tr> 的范围,hover时同时修改背景色和边框颜色:

table {
  border-collapse: collapse;
  width: 100%;
}
tr {
  /* 用透明边框模拟行间距 */
  border-top: 5px solid transparent;
  border-bottom: 5px solid transparent;
}
/* 移除第一行的上边框,避免顶部出现多余间距 */
tr:first-child {
  border-top: none;
}
/* hover时统一设置背景色和边框色 */
tr:hover {
  background-color: red;
  border-color: red;
}
/* 保持单元格内边距,避免内容挤在一起 */
td {
  padding: 8px;
}

内容的提问来源于stack exchange,提问作者Yaşar Emre Doğru

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 21:46:04