Reputation: 29
I am new to react and trying to make a simple component and set its background image using separate css file.
My App.js component:
import React from "react";
import "./styles.css";
export default function App() {
return (
<div className="App">
<div className="header-img">
{/* <img src={require('./header.jpg')} alt='header-img'/> */}
</div>
</div>
);
}
The CSS file:
*{
margin: 0;
padding: 0;
border: 0;
box-sizing: border-box;
}
.header-img{
width: 100%;
height: 426px;
margin-top: 50px;
background-image: url('./header.jpg');
background-size: cover;
background-repeat: no-repeat;
background-position: center;
/* background-color: aquamarine; */
}
Here is CodeSandBox link https://codesandbox.io/s/clever-silence-cvhyt?file=/src/styles.css:0-309
Upvotes: 2
Views: 1602
Reputation: 53994
Using files through pure CSS will work only on static files, so you need to put your images in the public
folder.
That's because React applications that bootstrapped with create-react-app
are using webpack
for bundling the src
folder, accessing a path like './header.jpg'
through CSS won't bundle the file.
// public/header1.jpg
.header-img {
background-image: url("./header1.jpg");
}
Upvotes: 5