如何实现三列布局左右列底部sticky粘性固定效果?
问题原因
- 你原来给
.left、.right设置了height: 100%,父容器.content高度为auto,会默认和最高的中间列等高,导致左右列高度被拉伸到和中间列一致,内部元素没有sticky滚动空间 position: sticky需要作用在你需要固定的底部元素上,而非作用在整个左右列容器上,且sticky元素的父容器不能设置overflow:hidden/auto/scroll,否则会失效
修复方案
首先修改HTML:给左右列最后需要粘住的.box添加专属类名.sticky-bottom
<!-- 左列最后一个box --> <div class="box sticky-bottom">stick here at bottom</div> <!-- 右列最后一个box --> <div class="box sticky-bottom">stick here at bottom</div>
然后修改CSS:
/* 先清除默认边距,避免滚动偏移 */ * { margin: 0; padding: 0; box-sizing: border-box; } .App { text-align: center; } .topheader { background: red; width: 100%; height: 50px; } .box { width: 100%; height: 200px; background: gray; } /* 新增sticky底部样式 */ .sticky-bottom { position: sticky; bottom: 0; } .content { width: 100%; height: auto; display: flex; /* 三列顶对齐,避免左右列内容默认错位 */ align-items: flex-start; gap: 20px; /* 按需调整列间距 */ } .left { background: blue; display: flex; flex-direction: column; width: 220px; } .center { background: yellow; width: 540px; height: auto; flex-shrink: 0; /* 避免中间列被挤压 */ } .right { background: green; display: flex; width: 220px; flex-direction: column; }
效果说明
修改后滚动页面时,左右列会先随页面整体上移,当左右列最底部的.sticky-bottom元素触碰到视口底部时,就会固定在该位置,中间列可以继续正常滚动,后续给中间列加无限滚动加载新内容的逻辑也不会影响左右列的固定效果。
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

