'Cant access image in App.css from public/images/img-2.jpg

I am creating a react app when I want a particular section to have a background image that I have in my images folder which is inside the public folder. Accessing those images seems to be working except for when I try to access them from App.css

Error: Failed to compile.

./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/App.css) Error: Can't resolve '/images/img-2.jpg' in 'C:\Users\shlok\OneDrive\Desktop\React\react-website-1\src' enter image description here

App.css

.services {
  background-image: url('/images/img-2.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  color: #fff;
  font-size: 100px;
}

.products {
  background-image: url('/images/img-1.jpg');
  background-position: center;
  background-size: fill;
  background-repeat: no-repeat;
  color: #fff;
  font-size: 100px;
}

.sign-up {
  background-image: url('/images/img-8.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  color: #fff;
  font-size: 100px;
}


Solution 1:[1]

The url should look like:

background-image: url('../public/images/img-2.jpg');

You need to get out of your src folder and get into your public folder and then look into the images there.


If the above approach doesn't work, it would be because of the following reason:
In React, it is sort of a compulsion to place the images inside the src folder. Otherwise they are not readily accessible from any code inside the components folder.

Try creating a new folder in your src directory and then shifting the images. Or else you can directly take the whole images folder and cut-paste inside your src folder.

Solution 2:[2]

Hey did you try giving the path from the public folder. As per your folder structure your images folder reside in public folder. Can you try giving the path like 'public/images/img-1.jpg'

Solution 3:[3]

background-image:  url(`${process.env.PUBLIC_URL}/images/image1.jpg`);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dhanishtha
Solution 2 Praful
Solution 3 Henry Ecker