You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSS position: sticky属性未按预期生效问题求助

解决position: sticky不生效的问题

你的.last元素sticky定位没生效,核心原因是:父容器.child2的高度仅由内部内容撑开(总共1000px),远小于页面的滚动高度(1000vh)。页面滚动时,.child2会整体向上滑出视口,.last根本没机会触发固定——sticky元素的固定范围被死死限制在父容器的边界里。

修复方法

给.child2加一行height: 100%,让它的高度和父容器(.parent)保持一致,这样.last就能在足够的空间里触发sticky效果:

.parent {
  display: flex;
  align-items: flex-start;
}

.parent>* {
  width: 100%;
}

.child1 {
  height: 1000vh;
  background-color: cyan;
}

.child2 {
  background-color: bisque;
  position: relative;
  height: 100%; /* 新增这行,让child2高度匹配父容器 */
}

.child2>* {
  border: 5px solid black;
}

.first {
  height: 500px;
}

.last {
  background-color: grey;
  position: sticky;
  top: 0;
  height: 500px;
}

为什么这样有效

.parent的高度由.child1的1000vh决定,给.child2设置height:100%后,它会拉伸到和.parent一样的高度。此时页面纵向滚动时,.last会在.child2的容器内滑动,当它碰到视口顶部(top:0)就会固定在那里,直到.child2的底部完全离开视口才会跟着继续滚动。

内容的提问来源于stack exchange,提问作者MD SOHEL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 06:27:38