如何实现滚动容器内子元素溢出覆盖,滚动停留在标题处?
实现滚动到标题后停止,内容溢出覆盖的嵌套容器
问题描述
需要实现嵌套容器效果:父滚动容器滚动到title元素后停止滚动,下方红色内容容器溢出显示在所有元素上方(类似下拉框表现)。但当前代码中,红色内容会撑开父滚动容器,导致滚动可以继续向下,不符合需求。
解决方案
通过调整元素定位属性,让溢出内容脱离滚动容器的文档流,同时固定标题在滚动容器底部,即可实现需求。修改后的代码如下:
<div style="width: 200px; background: white;"> <div style="max-height: 200px; overflow-y: auto; position: relative; border: 3px solid purple;"> <div style="height: 100px; background: blue;">box1</div> <div style="height: 100px; background: green;">box2</div> <div style="background: yellow; position: sticky; bottom: 0;"> <div>title</div> <div style="background: red; height: 400px; position: absolute; left: 0; top: 100%; width: 100%;"> content that should appear beneath title and overlap everything when it needs more space so the scrolling will stop at title </div> </div> </div> </div>
关键修改说明
- 将黄色容器设置为
position: sticky; bottom: 0;:让标题在滚动容器滚动到底部时固定在底部,同时黄色容器高度仅包含标题,不会被红色内容撑开,确保滚动容器的滚动高度到标题位置就停止。 - 红色内容容器设置
position: absolute; left: 0; top: 100%; width: 100%;:脱离滚动容器的文档流,不再占用滚动容器空间,而是定位在标题下方,自然覆盖其他元素。 - 滚动容器保留
position: relative;:作为绝对定位元素的参考父级,保证红色内容定位正确。 - 移除最外层容器的
overflow: hidden:避免溢出的红色内容被隐藏,确保其正常显示在所有元素上方。
内容的提问来源于stack exchange,提问作者usedtobemeonce
相关产品推荐
相关产品推荐

