网络上表格的一个普遍问题是,当内容量很大时,它们在小屏幕上的原生效果并不好,而且使它们可滚动的方法并不明显,特别是当标记可能来自 CMS,无法添加一个包装器时。
这个例子提供了一种在小空间中显示表格的方法。我们隐藏了 HTML 内容,因为它非常大,而且没有什么特别之处。在这个例子中,研究其 CSS 代码更有用。
13 等于: 23 等于: 33 等于: 43 等于: 53 等于: 63 等于: 73 等于: row 1: 1 row 1: 8 row 1: 27 row 1: 64 row 1: 125 row 1: 216 row 1: 343 row 2: 1 row 2: 8 row 2: 27 row 2: 64 row 2: 125 row 2: 216 row 2: 343 row 3: 1 row 3: 8 row 3: 27 row 3: 64 row 3: 125 row 3: 216 row 3: 343 row 4: 1 row 4: 8 row 4: 27 row 4: 64 row 4: 125 row 4: 216 row 4: 343 row 5: 1 row 5: 8 row 5: 27 row 5: 64 row 5: 125 row 5: 216 row 5: 343 row 6: 1 row 6: 8 row 6: 27 row 6: 64 row 6: 125 row 6: 216 row 6: 343 row 7: 1 row 7: 8 row 7: 27 row 7: 64 row 7: 125 row 7: 216 row 7: 343 row 8: 1 row 8: 8 row 8: 27 row 8: 64 row 8: 125 row 8: 216 row 8: 343 row 9: 1 row 9: 8 row 9: 27 row 9: 64 row 9: 125 row 9: 216 row 9: 343 row 10: 1 row 10: 8 row 10: 27 row 10: 64 row 10: 125 row 10: 216 row 10: 343 row 11: 1 row 11: 8 row 11: 27 row 11: 64 row 11: 125 row 11: 216 row 11: 343 row 12: 1 row 12: 8 row 12: 27 row 12: 64 row 12: 125 row 12: 216 row 12: 343 row 13: 1 row 13: 8 row 13: 27 row 13: 64 row 13: 125 row 13: 216 row 13: 343 row 14: 1 row 14: 8 row 14: 27 row 14: 64 row 14: 125 row 14: 216 row 14: 343 row 15: 1 row 15: 8 row 15: 27 row 15: 64 row 15: 125 row 15: 216 row 15: 343 row 16: 1 row 16: 8 row 16: 27 row 16: 64 row 16: 125 row 16: 216 row 16: 343 row 17: 1 row 17: 8 row 17: 27 row 17: 64 row 17: 125 row 17: 216 row 17: 343 row 18: 1 row 18: 8 row 18: 27 row 18: 64 row 18: 125 row 18: 216 row 18: 343 row 19: 1 row 19: 8 row 19: 27 row 19: 64 row 19: 125 row 19: 216 row 19: 343 row 20: 1 row 20: 8 row 20: 27 row 20: 64 row 20: 125 row 20: 216 row 20: 343当查看这些样式时,你会注意到表格的 display 属性已被设置为 block。虽然允许滚动,但表格失去了一些完整性,而且表格单元格会尽量变小。为了缓解这个问题,我们在 上将 white-space 设置为 nowrap。然而,我们没有对 进行设置,以避免长标题迫使列的宽度超过显示数据所需的宽度。
为了在向下滚动时保持表头在页面上,我们在 元素上将 position 设置为 sticky。注意,我们没有将 border-collapse 设置为 collapse,因为如果我们这样做,表头就不能与表格的其他部分正确分开。
csstable,th,td { border: 1px solid;}table { width: 100%; max-width: 400px; height: 240px; margin: 0 auto; display: block; overflow-x: auto; border-spacing: 0;}tbody { white-space: nowrap;}th,td { padding: 5px 10px; border-top-width: 0; border-left-width: 0;}th { position: sticky; top: 0; background: #fff; vertical-align: bottom;}th:last-child,td:last-child { border-right-width: 0;}tr:last-child td { border-bottom-width: 0;}结果