Search code examples
cssbackgroundbackground-image

Background Image not showing despite having correct path as URL


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


Solution

  • 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