background-repeat: no-repeat 是让背景图不重复的唯一可靠写法,但需确保路径正确、容器有尺寸(如 min-height: 100vh)、未被 !important 覆盖,并配合 background-position 定位,且简写时 no-repeat 必须紧跟 url() 后。

background-repeat: no-repeat 是让图片不重复的唯一可靠写法,但光写这行不够——90% 的“不重复失效”其实是因为路径错、容器没尺寸,或被全局样式覆盖。
为什么写了 no-repeat 还是平铺?
浏览器默认确实会平铺,但很多项目里有重置 CSS,比如 * { background-repeat: no-repeat; } 或框架自带的 Normalize.css,反而把你的 body 本该平铺的图给锁死了。更常见的是:你写了 no-repeat,但图片路径 404 了,浏览器干脆不渲染背景,你以为“没显示”,其实是“根本没加载”。
- 打开开发者工具 → Network 标签页,过滤
img或media,看背景图是否返回 404 - 检查路径是否相对于 CSS 文件位置:外部 CSS 中写
url("../images/bg.jpg"),不是相对于index.html - 确认没被其他规则用
!important覆盖,比如某处写了body { background-repeat: repeat !important; }
no-repeat 必须搭配 background-position 才可控
只写 background-repeat: no-repeat,图会默认贴左上角。如果容器宽高远大于图片,你会看到图孤零零在角落,其余全是背景色(或透明)。这时候必须加 background-position 控制落点:
- 居中显示:
background-position: center;或background-position: 50% 50%; - 固定右下角:
background-position: right bottom; - 偏移 20px:
background-position: 20px 20px;
注意:background-position 对 repeat 无效,但对 no-repeat 是刚需。
容器没尺寸,no-repeat 也白搭
body 默认高度为 0,尤其页面内容空或很短时。即使你设了 background-image 和 no-repeat,实际渲染区域可能就几像素高,图根本“展不开”。解决方法很简单:
- 加
min-height: 100vh;让它至少占满视口 - 顺手清掉浏览器默认外边距:
margin: 0;,否则背景会被挤出顶部 - 若要撑满整个文档(含滚动后内容),得双保险:
html { min-height: 100%; }+body { min-height: 100%; }
background 简写时 no-repeat 容易写错顺序
想一行写完,顺序不能乱:background: url("logo.png") no-repeat center / contain; 是对的;但写成 background: url("logo.png") center no-repeat; 就会失效——no-repeat 必须紧跟在 url() 后面,且 / 前不能插其他值。
多层背景时更要小心:background: url("a.png") no-repeat, url("b.png") repeat;,每个图的 repeat 类型必须一一对应,漏一个或错位,整条规则可能被忽略。
最容易被忽略的其实是:no-repeat 不代表“图一定可见”,它只管“不重复”,而图能不能显示,取决于路径、容器尺寸、z-index 层叠和 MIME 类型是否被服务器正确返回。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











