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

如何实现元素初始固定在视口底部,滚动至容器底部后随页面同步滚动?

如何实现元素初始固定在视口底部,滚动至容器底部后随页面同步滚动?

嘿,这个需求刚好是CSS position: sticky的拿手好戏!完全不用写JavaScript就能搞定,我来给你捋捋怎么改~

你之前尝试的fixed和absolute都没踩中关键点——sticky属性专门用来实现这种「在特定范围内保持固定,超出范围后跟随父容器滚动」的效果,完美匹配你的场景。

核心解决方案

只需要修改.learn-more的定位属性,把原来的position: absolute换成position: sticky,再加上bottom: 0就行。同时确保父容器#section-one是它的直接滚动上下文(你的代码里已经满足这个条件了)。

修改后的完整代码

CSS部分

:root {
  --blue: #007bff; /* 补全变量,避免hover时出错 */
}

#section-one {
  position: relative;
  background: #c3c3c3;
  padding: 40px;
  height: 120vh;
  text-align: center;
}

.learn-more {
  display: flex;
  flex-direction: column;
  border: none;
  width: 100%;
  transition: all .4s;
  position: sticky; /* 关键修改:换成sticky */
  bottom: 0; /* 固定在视口底部,直到父容器底部到达视口 */
  z-index: 10; /* 可选:避免被其他元素遮挡 */
  text-align: center;
  background: #c3c3c3; /* 可选:继承父容器背景,避免滚动时露出下方内容 */
}

.learn-more:hover {
  color: var(--blue);
  transition: all .4s;
  transform: translateY(-10px);
}

.caret {
  transform: scale(2,1);
  margin-top: -10px;
}

#section-two {
  height: 100vh;
  padding: 40px;
  background: #d3d3d3;
}

HTML部分

<section id="section-one">
  <h1>Section One</h1>
  <ul>
    <li>"Learn More" below should be visible any time section one is on screen.</li>
    <li>Could be in the middle of the section if the bottom of s1 is off-screen</li>
    <li>or if the bottom is on-screen then it should stop at the bottom of the section.</li>
  </ul>
  <a href="#section-two" class="learn-more">
    <div class="font-bold text-lg">Learn More</div>
    <div class="caret font-bold text-xl">⌄</div>
  </a>
</section>
<section id="section-two">
  <h2>Section Two</h2>
  <p>"Learn More" should never be in this section, and should scroll up with the bottom of section 1 above</p>
</section>

效果说明

  • 页面加载时:按钮会固定在视口底部,哪怕section-one的底部还在视口外,用户也能清晰看到它;
  • 滚动过程中:当你向下滚动到section-one的底部进入视口后,按钮就会「粘」在section-one的底部,跟着section-one一起向上滚动,绝对不会跑到section-two的区域里;
  • hover效果:你原来写的悬停动画完全不受影响,依然正常工作。

几个注意事项

  • 确保#section-one没有设置overflow: hidden或者overflow: scroll(除非你特意要让它成为独立滚动容器),否则sticky会失效;
  • 给按钮加background: #c3c3c3是为了滚动时避免露出下方section-two的背景,让视觉效果更连贯;
  • z-index是可选的,如果页面上有其他层级较高的元素,加上它能保证按钮始终可见。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 11:14:29