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

如何用CSS固定顶部div栏,滚动时仍可完整显示下方div?

解决方案:固定顶部栏+滚动切换内容区块

这问题我太熟悉了!其实你离正确答案只差一步——用position: fixed把顶部栏钉在视口顶部,再给下方内容留出对应的空间,就能完美实现需求。我直接给你写个可运行的示例,看完你就明白为啥之前的方法没生效了:

HTML 结构

<div id="bar">顶部固定栏</div>
<div class="content-wrapper">
  <div id="one">第一个内容区块</div>
  <div id="two">第二个内容区块</div>
</div>

CSS 样式

* {
  /* 清除默认内外边距,避免干扰布局 */
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#bar {
  /* 核心:固定在视口顶部 */
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 15vh;
  background-color: #42b983;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  /* 加个z-index确保不会被内容盖住 */
  z-index: 999;
}

.content-wrapper {
  /* 给顶部栏留出15vh的空间,避免内容被遮挡 */
  margin-top: 15vh;
}

#one, #two {
  /* 每个内容区块占满剩余视口高度 */
  height: 85vh;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
}

#one {
  background-color: #f5f5f5;
}

#two {
  background-color: #eaeaea;
}

为啥之前的方法没生效?

  • 用position: relative/absolute时,元素仍在文档流内(relative)或依赖父级定位(absolute),没法直接固定在视口顶部;
  • 单独给#one加top:15vh但没处理文档流,会导致内容重叠或者布局混乱;
  • 这个方案的核心是:position: fixed让顶部栏脱离文档流,固定在视口,然后用margin-top给下方内容容器让出顶部栏的高度,每个内容区块设85vh刚好填满剩余视口,滚动时自然切换显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 07:48:51