I was adding a background image in my react js . But it is showing an error

Viewed 126

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.

2 Answers

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%;
}

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');
Related