仅用 CSS 实现行和列高亮

Avatar of Chris Coyier
Chris Coyier 发布

DigitalOcean 提供适用于旅程各个阶段的云产品。 立即开始使用 $200 免费信用额度!

在 CSS 中,高亮表格行非常简单。 tr:hover { background: yellow; } 可以很好地实现。 但是,高亮列一直比较棘手,因为没有单个 HTML 元素可以作为列中表格单元格的父元素。 一点点 JavaScript 可以轻松处理,但 Andrew Howe 最近给我发邮件分享了他发现的技巧,在 StackOverflow 上,由 Matt Walton 发布。

这个技巧已经有些年头了,所以我只是想把它整理一下,然后发布到这里。

技巧是使用 <td> 上的巨大伪元素,并通过表格溢出隐藏

您无法从 CSS 中真正了解表格的大小,因此只需将伪元素的高度设置为该高度的一半,并设置一个负的顶部值。

table {
  overflow: hidden;
}

tr:hover {
  background-color: #ffa;
}

td, th {
  position: relative;
}
td:hover::after,
th:hover::after {
  content: "";
  position: absolute;
  background-color: #ffa;
  left: 0;
  top: -5000px;
  height: 10000px;
  width: 100%;
  z-index: -1;
}

负的 z-index 会将它保留在内容下方。 负的 z-index 是一种有趣的技巧,但要注意,此表格不能嵌套在具有背景的其他元素中,否则高亮会显示在它们下方。

您可以在此处查看实际效果

查看 CodePen 上 Chris Coyier (@chriscoyier) 的 仅用 CSS 实现行和列高亮 示例。

让它在触控设备上也能使用

悬停伪类在触控设备上只能勉强工作。 首先,元素需要可聚焦,而表格单元格默认不可聚焦。 当然,您可以向表格单元格添加点击事件处理程序,并在 JavaScript 中完成所有操作,但这里介绍了一种方法,可以将大部分工作保留在 CSS 中

// Whatever kind of mobile test you wanna do.
if (screen.width < 500) {
  
  // :hover will trigger also once the cells are focusable
  // you can use this class to separate things
  $("body").addClass("nohover");

  // Make all the cells focusable
  $("td, th")
    .attr("tabindex", "1")
    // When they are tapped, focus them
    .on("touchstart", function() {
      $(this).focus();
    });
  
}

然后,在 CSS 中添加 :focus 样式。

td:focus::after,
th:focus::after { 
  content: '';  
  background-color: lightblue;
  position: absolute;  
  left: 0;
  height: 10000px;
  top: -5000px;
  width: 100%;
  z-index: -1;
}

td:focus::before {
  background-color: lightblue;
  content: '';  
  height: 100%;
  top: 0;
  left: -5000px;
  position: absolute;  
  width: 10000px;
  z-index: -1;
}

在我的最终演示中,我对 CSS 选择器进行了更精细的处理,确保空表格单元格不会触发任何操作,<thead> 中的表格标题只选择列,<tbody> 中的表格标题只选择行。

您可以在 最终演示 中看到这一点。 这里展示了触控功能。