skip to Main Content

I’m trying to add a background image in my React Project, but it’s not showing up despite having correct relative path as URL.
Here is my "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>
          );
        }
    

And following is the "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;
}

And here is the codesandbox example: https://codesandbox.io/s/festive-scott-h28j42?file=/src/styles.css:0-294

2

Answers


  1. On codesandbox, you have to put images in public folder, just move your "images" folder there.

    Second : your pixabay url seems to not pointing on image file, try with cdn file url :
    /* background-image: url(https://cdn.pixabay.com/photo/2023/07/29/08/31/snow-felberich-8156446_1280.jpg); */

    Edited codesandbox : https://codesandbox.io/s/backgroundimage-forked-5n5fw8?file=/src/styles.css

    Login or Signup to reply.
  2. Check the File Path:
    Make sure that the path to your background image is correct. You’ve mentioned that the path is "./images/img-2.jpg", which means that the "img-2.jpg" image file should be located in a folder named "images" within the same directory as your "styles.css" file.

    css
    Copy code
    project-folder/
    ├── src/
    │ ├── App.js
    │ ├── styles.css
    │ └── images/
    │ └── img-2.jpg
    ├── …

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search