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

添加background-attachment: fixed后背景图过大,background-size: cover失效求助

解决方案:固定背景图同时保持background-size: cover生效

嘿,我之前也踩过这个坑!当你给背景图添加background-attachment: fixed时,background-size: cover的参考对象会从元素本身变成整个视口(viewport),这就导致背景图被拉伸到整个浏览器窗口大小,而不是适配你的.site-header元素,所以标题才会被遮得没法读。

这里有个靠谱的替代方案,用伪元素来分离背景层和内容层,既能实现固定背景的滚动效果,又能让background-size: cover正常工作:

.site-header {
  position: relative;
  /* 根据你的需求设置合适的最小高度,保证标题有足够显示空间 */
  min-height: 450px;
  /* 移除原来的background属性 */
}

.site-header::before {
  content: "";
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url("https://howtogetrippedathome.com/wp-content/uploads/2018/01/How-To-Get-Ripped-At-Home-Header-Image.png") top center;
  background-size: cover;
  z-index: -1; /* 把背景层放在内容下方 */
}

原理说明:

  • 用::before伪元素创建一个占满整个视口的固定层,它的background-size: cover会基于视口计算,完美适配屏幕。
  • .site-header设置为相对定位,里面的标题等内容会正常显示在这个固定背景层之上,不会被遮挡。
  • 当页面滚动时,这个伪元素背景会保持固定,body内容从它上方滑过,正好实现你想要的效果。

如果你需要调整背景图的显示位置,可以修改background属性里的top center为其他值(比如center center),直到达到你满意的效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:07:56