html - 固定表头滚动水平和垂直 CSS ONLY

标签 html css scroll

首先,是否可以仅使用 CSS 来实现?

我已经构建了一个可以水平和垂直滚动的表格,但是,我希望将 header 封装在它的容器中,而不是出现在包装器之外。因此,当您水平滚动时,相应的标题与其指定列的内容一致。

使用 position: absoluteposition: static 的不同变体给我一些预期的结果,但不是完整的解决方案。

您会注意到应用到 section 元素的宽度,以提供在封闭区域内水平滚动的效果。

这是我目前所拥有的 JSFIDDLE 示例和下面的 CSS 以供引用

https://jsfiddle.net/ko6qco1r/

html, body{
  margin:0;
  padding:0;
  height:100%;
}
section {
  position: relative;
  border: 1px solid #000;
  padding-top: 37px;
  background: grey;
  width: 300px;
}

.container {
  overflow-y: auto;
  overflow-x: scroll;
  height: 200px;
}
table {
  border-spacing: 0;
  width:100%;
}
td + td {
  border-left:1px solid #eee;
}
td, th {
  border-bottom:1px solid #eee;
  background: white;
  color: #000;
  padding: 10px 25px;
}
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 black;
}
th:first-child div{
  border: none;
}

最佳答案

这是 W3C 的不作为给我们带来的另一个有趣挑战(如垂直居中)。同样与垂直居中一样,您不能使用 position: fixed; 将固定标题放在带有水平滚动条的表格上。在 thead 上元素。但是您确实有几个选择。

选项 1 - 水平滚动 ( http://codepen.io/staypuftman/pen/JXbpvZ )

此处的关键是将表格布局重新设置为 table-layout: fixed; CSS-tricks has a good piece on this approach然后放一个min-width当您希望滚动条出现时,容器上的值。这使得表格可以从左向右滚动,并在较小的设备上保持列标题的完整性。但标题不固定。

选项 2 - 固定 header ( https://jsfiddle.net/dPixie/byB9d/3/light/ )

你的代码看起来像是抄袭了这个人的作品,所以我想我应该在这里重新发布以表彰他。这种方法创建了一系列 <div>反射(reflect) <th> 内容的元素元素,并使用一些非常有创意的定位技术来让它发挥作用。

Salzar design 上有一个更好的破旧显示一些 examples并详细解释了所有复杂的操作才能做到这一点。

关于html - 固定表头滚动水平和垂直 CSS ONLY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36014802/

相关文章:

html - 我希望 <div> 位于正中心;不知道如何处理底部和右边距

html - 如何将全宽元素插入三列 CSS 网格布局?

javascript - 使输入显示在其他元素之上

android - Webkit 转换 : multiple properties on Android

html - 100% 高度 div 的滚动条

html - 将第二行文本的开头与第一行对齐

css - 移动设备无法正确呈现响应式电子邮件

css - HTML : Scale images using max height/width

Vim 滚动而不改变光标在屏幕上的位置

iOS 13 Blob pdf 文件的滚动问题(无法用一根手指滚动)