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

如何用CSS实现背景随header滚动后固定的stickyfixed效果

纯CSS实现方案

可以用CSS滚动驱动动画(Scroll-driven Animations)实现该效果,原生浏览器层面渲染无性能损耗,目前Chrome 115+、Edge 115+、Safari 16.4+均已支持。

前置约定

先在全局定义header的固定高度变量,方便统一维护:

:root {
  --header-height: 80px; /* 替换为你实际的header高度 */
}

默认状态样式(header为fixed的常规视口)

保留你原本的逻辑即可:

header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: var(--header-height);
  z-index: 10;
}
#container::before {
  content: '';
  position: fixed;
  top: var(--header-height);
  left: 0;
  width: 100%;
  height: 100vh;
  background: url(你的背景图路径) center/cover no-repeat;
  z-index: -1;
}
/* 默认状态下container加padding避免内容被fixed的header遮挡 */
#container {
  padding-top: var(--header-height);
}

短视口状态样式(header切换为static)

在你原本切换header为static的媒体查询中,添加滚动驱动动画控制背景伪元素的位移:

/* 替换为你自己判断短视口的媒体查询条件 */
@media (max-height: 600px) {
  header {
    position: static;
  }
  #container {
    padding-top: 0;
  }
  #container::before {
    top: 0;
    /* 绑定滚动驱动动画 */
    animation: bg-position linear both;
    animation-timeline: scroll(root);
    /* 动画触发范围:滚动距离从0到header高度的区间 */
    animation-range: 0 var(--header-height);
  }
  @keyframes bg-position {
    /* 滚动距离为0时,背景图向下偏移header高度,刚好贴在header底部不被遮挡 */
    0% {
      transform: translateY(var(--header-height));
    }
    /* 滚动距离等于header高度时,偏移归零,背景贴在视口顶部 */
    100% {
      transform: translateY(0);
    }
  }
}

兼容性降级

不支持滚动驱动动画的浏览器会自动降级为你原本的top:0方案,核心功能不受影响,仅背景图初始位置的体验有差异。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:06:07