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

CSS fixed定位实现两个顶部区块固定 仅内容区滚动

实现两个区块固定、仅内容区滚动的方案

核心思路是给两个需要常驻可见的区块都设置fixed固定定位,按垂直排布顺序设置对应的顶部偏移量,同时给滚动内容区预留足够的顶部间距,避免内容被固定区块遮挡。

具体修改步骤

  • 给已固定的.header补充top:0和层级属性,确保它固定在视口最顶部,不会被其他页面元素覆盖
  • 给.buttons-section添加fixed定位,top值设置为.header的高度,让它刚好紧贴在header下方,同样设置足够的层级
  • 给.content设置顶部内边距,数值等于header和按钮区的高度之和,抵消固定元素脱离文档流造成的内容遮挡问题

完整修改后代码

CSS 部分

.header {
  background-color: red;
  width: 100%;
  position: fixed;
  top: 0;
  /* 以下高度为示例值,可根据实际设计调整 */
  height: 50px;
  z-index: 100;
}

.buttons-section {
  background-color: yellow;
  position: fixed;
  width: 100%;
  /* top值与header高度保持一致,实现无缝衔接 */
  top: 50px;
  /* 以下高度为示例值,可根据实际设计调整 */
  height: 40px;
  z-index: 99;
}

.content {
  background-color: green;
  /* 顶部间距 = header高度 + 按钮区高度,避免内容被遮挡 */
  padding-top: 90px;
}

HTML 部分

原有DOM结构不需要任何调整,直接复用即可:

<!DOCTYPE html>
<html>  
<body>
  <div>
    <div class="header">
      APP HEADER - fixed position always
    </div>
    <div>
      <div class="buttons-section">
        <button>Test button 1</button>
        <button>Test button 2</button>
      </div>

      <div class="content">
        <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
        <!-- 剩余长文本内容与原代码完全一致即可 -->
      </div>
    </div>
  </div>
</body>
</html>

适配动态高度的可选方案

如果固定区块的高度不固定(比如header适配不同端尺寸、按钮区内容动态变化),可以不用写死高度和偏移值,通过JS在页面加载、窗口resize时实时获取两个固定区块的实际高度,动态计算.buttons-section的top值和.content的padding-top值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 00:03:20