2

I have seen on the internet they were telling to add image in the public folder . So i added my image into the public folder by creating a sub folder name img in which i place my image "mario.png" in it.

As i wanted to add that image as the background image so i wrote this code in my index.css


body{
    margin:0;
    padding: 0;
    font-family: sans-serif;
    background: url(/img/mario.png);
    background-size: 100%;
    background-position: bottom;
    background-color: #95e8f3;  
    min-height: 100%;
}

and still it was not working it was showing the error : ** ./src/index.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/index.css) Error: Can't resolve '/img/mario.png' in 'D:\Users\PIRATES\Desktop\cool\src' **

This is the folder structure

But when i created a asset folder in src then it was working but i want to know why it is not working when i am placing my image in the public folder.

  • 1
    url value should be in quotes url('/img/mario.png') – Punith Mithra Apr 16 '21 at 05:14
  • @PunithMithra i have added the double quotes even it is not working. – TUSHAR YADAV Apr 16 '21 at 05:15
  • Have you tried this https://stackoverflow.com/questions/57162841/use-images-in-css-files-with-reactjs? – Dhana D. Apr 16 '21 at 05:17
  • 1
    Check this answer: https://stackoverflow.com/questions/64852112/create-react-app-4-0-cannot-resolve-image-path-in-public-folder – fast-reflexes Apr 16 '21 at 05:19
  • @fast-reflexes Yes this is working . But everyone was telling that you should add the image in the public folder and the react automatically detects it is in public folder so this was not working and i just want to know why ? – TUSHAR YADAV Apr 16 '21 at 05:26
  • For me, it works to put it in the public folder. If you use it like `` does it work then? – fast-reflexes Apr 16 '21 at 05:30
  • @fast-reflexes yes it works for me. If i am adding the img tag. Thanks for the link of the above post. – TUSHAR YADAV Apr 16 '21 at 05:38
  • So then it seems to be something special with this css processing (the postcss-loader). As I said it works for me even when used as a background in css (but I don't know if I use this postcss-loader) but I don't know why it doesn't work for you. Now at least you know that you can use the public folder for other purposes. – fast-reflexes Apr 16 '21 at 05:54

2 Answers2

0

You are not using url function properly. docs

body{
    margin:0;
    padding: 0;
    font-family: sans-serif;
    background: url("/img/mario.png");
    background-size: 100%;
    background-position: bottom;
    background-color: #95e8f3;  
    min-height: 100%;
}
Punith Mithra
  • 608
  • 5
  • 9
0

You have to add the relative path inside the url function, not the absolute path from the root of the project.

Considering your screenshot, you have to write something like this:

background: url('../public/img/mario.png');
Just Mohit
  • 141
  • 1
  • 13