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

CSS实现sticky笔记本组件滚动效果 解决背景图溢出问题

问题根因

你当前代码出现背景溢出,核心是三点逻辑错误:

  • 双层sticky同级嵌套:.container和外层直接子级背景img都设置了position: sticky,两者为同级DOM关系,滚动时偏移量计算独立,无法形成父级裁剪子级的约束
  • 裁剪容器无固定定位基准:.note设置了overflow: hidden但自身不是sticky定位元素,滚动过程中裁剪区域会随父元素整体上移,无法把背景限制在视口内的笔记本区域
  • 滚动区间设置错误:给最外层父元素加600px顶部内边距,会让sticky元素的触发阈值偏移,导致元素还没完全进入视口就开始吸顶,背景提前露出边界
可直接复用的实现方案

移除冗余的双层sticky逻辑,仅给笔记本可视容器设置吸顶属性,将背景图移入容器内部通过父级overflow: hidden自动裁剪,即可实现背景始终驻留视口、不超出笔记本边界的效果。

修正后CSS代码

.project-rules__note {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
}

/* 外层容器撑开滚动区间,高度可根据实际内容长度调整 */
.project-rules__note .container {
  width: 68vw;
  height: 300vh;
  position: relative;
}

/* 笔记本吸顶可视区域 */
.project-rules__note .note {
  width: 100%;
  height: 100vh;
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  /* 核心:裁剪所有超出笔记本边界的内容 */
  overflow: hidden;
}

/* 带阴影的笔记本外壳图层,层级最高 */
.project-rules__note .book {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 3;
  display: flex;
  align-items: center;
  justify-content: center;
}
.project-rules__note .book img {
  width: 100%;
  height: auto;
  max-height: 100vh;
  object-fit: contain;
}

/* 背景图层级最低,随吸顶容器固定在视口内 */
.project-rules__note .bg-note {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}
.project-rules__note .bg-note img {
  width: 53vw;
  height: auto;
}

/* 后续要加笔记本内的滚动内容,可新增该类,层级设为2夹在背景和外壳之间 */
.project-rules__note .note-content {
  position: absolute;
  z-index: 2;
  width: 70%;
  /* 自定义内容样式即可 */
}

修正后HTML结构

<div class="project-rules__note">
  <div class="container">
    <div class="note">
      <!-- 背景图移入笔记本容器内部,受overflow规则裁剪 -->
      <div class="bg-note">
        <img src="https://i.ibb.co/74d27jf/bgnote.jpg" alt="笔记本背景">
      </div>
      <!-- 笔记本内展示内容可加在这里 -->
      <!-- <div class="note-content">...</div> -->
      <!-- 带阴影的笔记本外壳 -->
      <div class="book">
        <img src="https://jukachu.github.io/Lottery-cards/src/notebook.png" alt="笔记本外壳">
      </div>
    </div>
  </div>
</div>

效果说明:滚动页面时.note容器到达视口顶部后自动吸顶,内部背景因和吸顶容器相对固定,不会出现向上溢出笔记本边界的问题;外层.container的300vh高度为滚动预留区间,可根据实际需要展示的内容长度自行调整。

内容的提问来源于stack exchange,提问作者Juka Chu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 19:54:18