CSS背景图在GitHub Pages部署后不显示,本地Live Server正常
问题:GitHub Pages部署后背景图无法加载(本地Live Server正常)
问题详情
- 需求:实现背景图全屏覆盖,将文本、用户名输入框及按钮置于背景图上方
- 异常现象:本地通过Live Server扩展运行时背景图显示正常,但部署到GitHub Pages后无法加载
- 相关代码:
CSS代码
.start-container { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%) scale(1); width: 100%; height: 100%; text-align: center; display: flex; flex-direction: column; flex-wrap: wrap; align-items: center; justify-content: center; background-image: url(/assets/images/start-window-image.webp); background-repeat: no-repeat; background-size: cover; }
HTML代码
<body> <div class="start-container"> <div class="start-title"> <h1>FOODle</h1> </div> <div class="start-body"> <h3>Enter a username:</h3> <input type="text" placeholder="Username" required> <button id="start-button">Start</button> </div> </div> </body>
解决方案
问题核心是背景图路径设置错误:
- 本地Live Server以项目文件夹作为根目录,
/assets/images/start-window-image.webp能正确定位到图片; - 但GitHub Pages的项目站点(非个人主页)根路径是
https://用户名.github.io/项目名/,原绝对路径会指向https://用户名.github.io/assets/images/...,而实际图片位置是https://用户名.github.io/项目名/assets/images/...,导致路径匹配失败。
两种修复方式:
- 使用相对路径:去掉路径开头的斜杠,改为相对当前CSS文件的路径
background-image: url(assets/images/start-window-image.webp);
(若CSS文件在子目录中,需根据层级调整,比如CSS在css/文件夹下则写成../assets/images/start-window-image.webp)
- 带项目名的绝对路径:在路径前加上项目名称前缀
background-image: url(/p2-project-foodle/assets/images/start-window-image.webp);
(此方式路径指向明确,但后续若修改项目名称,需同步调整路径)
额外验证:确认GitHub仓库中assets/images/start-window-image.webp文件存在,文件名、后缀无拼写错误。
内容的提问来源于stack exchange,提问作者yamesjames
相关产品推荐
相关产品推荐

