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

CSS背景图片无法在网站显示问题求助

解决背景图片无法显示的问题

我看了你的代码,问题大概率出在高度设置的参考值缺失上!

当你给.bg类设置height: 50%时,这个百分比是相对于父元素的高度来计算的,但你的父元素(默认是<body>和<html>)没有设置明确的高度值,浏览器根本不知道“50%”到底是多少像素,导致这个<div>实际上高度为0——自然看不到背景图。

给你两个可行的修改方案:

方案1:使用视口单位(vh)设置高度

直接用基于浏览器视口的高度单位,不需要依赖父元素的高度:

/* 先重置默认样式,避免边距干扰 */
html, body {
  margin: 0;
  padding: 0;
}

.bg {
  background: url('https://ak9.picdn.net/shutterstock/videos/12047219/thumb/10.jpg?i10c=img.resize(height:160)');
  height: 50vh; /* 表示占视口高度的50% */
  background-position: center;
  background-repeat: repeat-x;
  background-size: cover;
}

方案2:给父元素设置明确高度

如果一定要用百分比高度,就给根元素和body设置100%高度作为参考:

html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.bg {
  background: url('https://ak9.picdn.net/shutterstock/videos/12047219/thumb/10.jpg?i10c=img.resize(height:160)');
  height: 50%; /* 现在是相对于body的100%高度来计算,即视口高度的50% */
  background-position: center;
  background-repeat: repeat-x;
  background-size: cover;
}

另外补充两个小检查点(虽然你说试过很多方法,但还是提一下):

  • 确认图片URL可以直接在浏览器打开(避免链接失效或跨域问题)
  • 清除浏览器缓存后刷新页面,有时候缓存会导致图片加载异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:09:26