让 table 具有粘性 header 的最佳方法是什么?

What's the best way to have a table with sticky header?

我目前正在做的是 2 tables,一个用于 headers,一个用于数据,结合 table-layout:fixed 和每列的固定宽度。

我不喜欢这个解决方案,因为我必须不断调整宽度,而且当 table 布局不固定时,它们看起来不如自动调整的好。

我还考虑了一种 JS 解决方案,其中布局数据 table,然后 JS 获取每个列宽并将其应用于 header table。这样做的好处是 td 宽度由内容决定。问题是 table 内容可以动态变化,JS 脚本需要知道这一点,这样它才能重新计算宽度...呃。

有更好的方法吗?

最好使用一些插件,例如 jQuery Plugin for Fix Header Table

或者如果您想要纯粹的 CSS 并且想知道它是如何工作的。你可以试试下面的 fiddle https://jsfiddle.net/dPixie/byB9d/3/light/

如果 div 位于 TH

内,则显示内容
th {
  height: 0;
  line-height: 0;
  padding-top: 0;
  padding-bottom: 0;
  color: transparent;
  border: none;
  white-space: nowrap;
}
th div{
  position: absolute;
  background: transparent;
  color: #fff;
  padding: 9px 25px;
  top: 0;
  margin-left: -25px;
  line-height: normal;
  border-left: 1px solid #800;
}
th:first-child div{
  border: none;
}