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

滚动时文本下移图片固定的Flex布局实现问题求助

实现滚动时文本下移、图片固定的Flex布局效果

你的核心问题在于sticky定位未设置偏移值,且父容器高度限制了sticky的生效范围,同时文本没有足够的滚动空间来实现下移效果。以下是修正后的方案:

调整后的代码

HTML

<div>
  <div class="story3">
    <!-- 给文本单独包裹容器,方便控制滚动范围 -->
    <div class="text-container">
      <p class="header">Text of the div that will scroll down </p>
    </div>

    <div class="tft">
      <img src="14.png" alt="固定图片">
    </div>
  </div>
</div>

<div class="test">
  <p>Text below used for scroll </p>
</div>

CSS

.story3 {
  position: relative;
  top: 5rem;
  align-items: flex-start; /* 改为flex-start,避免文本垂直居中限制移动 */
  display: flex;
  background-color: rgb(21, 0, 255);
  min-height: 100vh; /* 用min-height替代height,允许内容超出容器高度 */
}

.tft {
  position: sticky;
  top: 0; /* 必须设置偏移值,sticky才会生效,这里固定在视口顶部 */
  height: 100vh; /* 让图片容器占满视口高度,保持固定显示 */
  flex-shrink: 0; /* 防止flex布局压缩图片宽度 */
  width: 50%; /* 可根据需求调整图片宽度占比 */
}

.tft img {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持图片比例,避免拉伸 */
}

.text-container {
  flex-grow: 1; /* 让文本容器占满剩余空间 */
  padding-bottom: 100vh; /* 给文本容器添加足够的底部内边距,创造滚动空间 */
  display: flex;
  align-items: center; /* 文本垂直居中,可根据需求调整 */
  padding: 0 2rem; /* 可选:添加左右内边距优化排版 */
}

.test {
  position: relative;
  top: 45rem;
}

关键修正点

  • sticky定位必须设置偏移值:给.tft添加top:0,明确固定位置,否则sticky不会生效。
  • 父容器高度调整:用min-height:100vh替代height:100vh,允许内容超出容器,给文本滚动留足空间。
  • 文本容器滚动空间:通过padding-bottom:100vh让文本容器高度远大于视口,滚动时文本会自然下移,而图片保持在视口内固定。
  • flex布局优化:给图片容器添加flex-shrink:0防止被压缩,调整align-items避免文本被居中限制移动。

内容的提问来源于stack exchange,提问作者Thor The dog

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 19:47:14