2

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

1 Answer 1

5

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");
}

Edit sweet-shaw-m6pwo

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot my friend ❤️

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.