纯CSS实现带中间栏sticky头部的百分比宽度三列布局
问题根因
sticky头部滚动后消失的核心原因是给.center设置了height:100%:
- 该属性把中间列高度锁死为视口高度,列内内容溢出到列元素外侧,sticky定位的吸附范围被限制在父容器(即
.center)的高度范围内,滚动距离超过视口高度后,头部就会随父容器一起离开视口,无法持续置顶。 - 原有代码中左右列的fixed定位逻辑没有问题,不需要调整三列的基础定位思路。
修正后完整代码
CSS代码
/* 重置默认边距,避免浏览器默认边距导致宽度溢出 */ * { margin: 0; padding: 0; box-sizing: border-box; } html,body{ height: 100%; } .wrap{ width: 100%; position: relative; } .left,.right{ width: 20%; top: 0; bottom: 0; position: fixed; height: 100%; } .center{ width: 60%; margin: 0 20%; } .left{ left: 0; background-color: #aaa; } .right{ right: 0; background-color: #ccc; } .head2{ background-color: tomato; width: 100%; position: sticky; top: 0; padding: 1em; } /* 测试内容区域样式 */ .test-content { padding: 1em; line-height: 2; }
HTML代码
<div class='wrap'> <div class='left'>左侧固定栏</div> <div class='right'>右侧固定栏</div> <div class='center'> <div class="head2">中间列粘性头部</div> <div class="test-content"> <!-- 此处填充足够多的测试文本,直到页面出现滚动条即可验证效果 --> hello world<br> hello world<br> </div> </div> </div>
实现效果说明
- 所有列宽均采用百分比设置:左右列各占20%,中间列占60%,无任何px单位的列宽定义,符合要求
- 粘性头部仅在中间列生效,由于移除了
.center的固定高度设置,列高随内容自适应,sticky定位的吸附范围和内容总高度一致,全程滚动时头部都会固定在视口顶部,不会提前消失 - 左右列通过fixed定位全程固定,滚动容器为页面根元素,鼠标在三列任意区域触发滚轮滚动时,只会驱动中间内容位移,左右列保持静止,交互逻辑和Twitter布局一致
- 全程无JS依赖,纯CSS实现,兼容所有支持sticky定位的现代浏览器
内容的提问来源于stack exchange,提问作者Frank Underwood
相关产品推荐
相关产品推荐

