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

背景图片无法显示求助:附相关HTML/CSS代码

解决方案

你的代码存在两个核心问题,导致背景图无法显示:

1. CSS属性写法错误

background-image 仅用于指定背景图路径,不能直接附加 no-repeat —— no-repeat 是 background-repeat 属性的取值,两者不能混写。你可以分开声明属性,或者使用复合属性 background 整合。

2. 空容器无高度

你的 <div> 内没有内容,且未设置高度,导致容器高度为0,背景图自然无法展示。不需要添加额外内容,只需给容器设置明确的宽高即可。

修正后的代码示例:

方式一:分开声明属性

.container {
  margin: 0 auto;
  background-image: url('https://images.unsplash.com/photo-1539683255143-73a6b838b106?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1000&q=80');
  background-repeat: no-repeat;
  background-size: 100px;
  /* 设置宽高,数值可按需调整 */
  width: 300px;
  height: 300px;
}
<div class="container"></div>

方式二:使用复合属性 background(更简洁)

.container {
  margin: 0 auto;
  background: url('https://images.unsplash.com/photo-1539683255143-73a6b838b106?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1000&q=80') no-repeat;
  background-size: 100px;
  width: 300px;
  height: 300px;
}

上述两种写法都能让空容器正常显示背景图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:55:21