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

如何实现页面背景图片固定,滚动内容时背景不移动?

实现滚动时固定的页面背景

要让背景图片在页面滚动时保持固定,只需在你的body CSS规则中添加background-attachment: fixed;属性,同时建议补充background-size和background-position属性优化背景图的显示效果,避免图片拉伸或显示不全。

完整的CSS代码如下:

body {
    background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(255, 255, 255, 0.5)), url('wallpaper.jpg');
    background-attachment: fixed; /* 核心属性:固定背景 */
    background-size: cover; /* 让背景图覆盖整个容器 */
    background-position: center; /* 让背景图居中显示 */
}

属性说明:

  • background-attachment: fixed:强制背景图片相对于视口固定,不会随页面滚动而移动。
  • background-size: cover:确保背景图按比例缩放,完全覆盖body区域,裁剪超出部分。
  • background-position: center:让背景图在容器中居中对齐,避免显示偏移。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 09:01:04