You need to enable JavaScript to run this app. 仅用CSS实现表格行/列hover时显示对应行/列最后一个td
优惠活动
大模型
产品
解决方案
定价
更多

仅用CSS实现表格行/列hover时显示对应行/列最后一个td

解决方案

要同时实现行和列的悬停显示效果,需要调整默认隐藏规则,并针对列的特性做针对性处理,以下是两种可行方案:

方案1:使用CSS :has 选择器(现代浏览器支持)

无需修改HTML结构,利用:has选择器检测鼠标悬停的列位置:

/* 默认隐藏:所有行的最后一个单元格 + 最后一行的所有单元格 */
tr td:last-child,
tr:last-child td {
  display: none;
}

/* 行悬停:显示当前行的最后一个单元格 */
tr:hover td:last-child {
  display: table-cell;
}

/* 列悬停:悬停某列任意单元格时,显示该列最后一行的单元格 */
table:has(td:nth-child(1):hover) tr:last-child td:nth-child(1),
table:has(td:nth-child(2):hover) tr:last-child td:nth-child(2),
table:has(td:nth-child(3):hover) tr:last-child td:nth-child(3) {
  display: table-cell;
}
<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
  </tr>
  <tr>
    <td>4</td>
    <td>5</td>
    <td>6</td>
  </tr>
  <tr>
    <td>7</td>
    <td>8</td>
    <td>9</td>
  </tr>
</table>

方案2:兼容旧浏览器(添加列标识类)

如果需要兼容不支持:has的浏览器,给每个单元格添加对应列的类名即可:

/* 默认隐藏规则 */
tr td:last-child,
tr:last-child td {
  display: none;
}

/* 行悬停效果 */
tr:hover td:last-child {
  display: table-cell;
}

/* 列悬停效果:关联同列的最后一行单元格 */
tr:not(:last-child) .col1:hover ~ tr:last-child .col1,
tr:not(:last-child) .col2:hover ~ tr:last-child .col2,
tr:not(:last-child) .col3:hover ~ tr:last-child .col3 {
  display: table-cell;
}
<table>
  <tr>
    <td class="col1">1</td>
    <td class="col2">2</td>
    <td class="col3">3</td>
  </tr>
  <tr>
    <td class="col1">4</td>
    <td class="col2">5</td>
    <td class="col3">6</td>
  </tr>
  <tr>
    <td class="col1">7</td>
    <td class="col2">8</td>
    <td class="col3">9</td>
  </tr>
</table>

关键说明

  • 用display: table-cell替代display: block,避免单元格布局错乱,保持表格原生样式。
  • 方案1的:has选择器支持Chrome 101+、Firefox 121+、Safari 15.4+,旧浏览器请选用方案2。
  • 列悬停的核心是通过单元格的位置或类名,关联触发最后一行对应位置的单元格显示。

内容的提问来源于stack exchange,提问作者Miki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 12:35:19