我想要一个粘性标题和水平滚动表。
我不想在表内的垂直滚动。它应该与页面滚动。所以没有设置表的高度。这甚至可能吗?
下面是一个不工作的例子:https://codepen.io/fwitkowski/pen/zYEQvvg
当我从table-container中删除overflow:auto时,position sticky工作得很好。
.table-container {
max-width:350px;
overflow-x:auto; /* for horizontal scroll */
position: relative; /* relative to the normal flow */
border: solid 5px red /* for reference */
}
字符串
2条答案
按热度按时间ezykj2lf1#
根据the MDN documentation:
一个粘性元素“粘”到它最近的具有“滚动机制”的祖先(当
overflow
是hidden
,scroll
,auto
,或overlay
时创建),即使该祖先不是最近的实际滚动祖先。在W3C repo上有一个活跃的GitHub问题在讨论这个问题,该repo自2017年以来一直在运行。已经提出了各种解决方案,但它们似乎都依赖于向表/表容器添加固定高度,或using Javascript as in this answer。
至少在目前,这不是原生支持的东西。
nuypyhwy2#
带有
position:sticky
的头文件想贴在它们的父文件(表格)的顶部,而不是窗口的顶部,因为表格有overflow-x:scroll
。我想出了一个简单的解决方法,它不依赖于固定的高度或自定义的滚动条。它只使用JavaScript。技巧是将表分成两个表。(
tableHeaders
)和一个body表(tableBody
)。tableHeaders
有overflow-x:hidden
,tableBody
有overflow-x:scroll
。现在头不再在表内,正文可以滚动。唯一的问题是头不滚动,但我们可以通过将其匹配到tableBody
使用onscroll
事件滚动。将两个表都 Package 在一个div中,以获得以表体结尾的粘性效果。
我们需要做的最后一件事是确保
tableHeaders
中的列宽与tableBody
的标题中生成的列宽相匹配。我们可以用一点JavaScript来处理这个问题。在内容加载后在某处调用它。字符串
**注意:**我在Blazor环境中,所有这些都被 Package 到一个组件中,其中
<thead>
作为RenderFragment
传递并自动复制。如果是其他情况,我可能会使用JavaScript将头克隆到粘性表中,而不是弄乱标记。**提示:**如果页面顶部有其他粘性或固定元素,则应该等于它们的高度。我有另一个example,它显示了如何自动处理这个问题。
型