我正在尝试在我的 React 项目中添加背景图像,但尽管有正确的相对路径作为 URL,但它没有显示。 这是我的“App.js”:
import "./styles.css";
export default function App() {
return (
<div className="App">
<h1>Hi All!</h1>
<h2>Please guide why the background image isn't showing here???</h2>
</div>
);
}
以下是“styles.css”:
.App {
font-family: sans-serif;
text-align: center;
background: aqua;
height: 100vh;
background-image: url(./images/img-2.jpg);
/* background-image: url(https://pixabay.com/photos/dandelion-seeds-dew-dewdrops-445228/); */
background-size: cover;
background-repeat: no-repeat;
}
这是codesandbox示例:https://codesandbox.io/s/festive-scott-h28j42?file=/src/styles.css:0-294
在codesandbox上,您必须将图像放在公共文件夹中,只需将“图像”文件夹移动到那里即可。
第二:你的 pixabay url 似乎没有指向图像文件,请尝试使用 cdn 文件 url :
/* background-image: url(https://cdn.pixabay.com/photo/2023/07/29/08/31/snow-felberich-8156446_1280.jpg); */