如何让子div始终覆盖可滚动父div?求纯CSS解决方案
解决方案:利用fixed定位+transform创建包含块
要实现.scroll-indicator始终覆盖.scroll-container的可视区域且不随内容滚动,同时不增加额外DOM层级,可以通过fixed定位结合transform堆叠上下文的方式实现:
修改后的CSS代码
.scroll-container { position: relative; width: 200px; height: 200px; overflow: auto; border: 1px solid blue; transform: translateZ(0); /* 创建堆叠上下文,让fixed元素以自身为包含块 */ } .scroll-item { height: 50px; } .scroll-indicator { position: fixed; inset: 0; /* 等同于top:0; left:0; right:0; bottom:0,完全覆盖父容器 */ border: 1px solid red; margin: 0; /* 清除默认边距 */ pointer-events: none; /* 可选:允许下层内容接收点击事件 */ }
原理说明
transform: translateZ(0)会让.scroll-container创建新的堆叠上下文,此时内部的fixed定位元素会以该容器为定位参考,而非整个浏览器视口。position: fixed配合inset:0可让.scroll-indicator完全填充.scroll-container的可视区域,且不会随容器内的内容滚动而移动。- 若需要下层内容可交互,添加
pointer-events: none可让点击事件穿透到.scroll-item上。
内容的提问来源于stack exchange,提问作者wallop
相关产品推荐
相关产品推荐

