score:27

Accepted answer

just use a / before the name, this will make it relative to the output root, which includes anything in the public folder (provided the finished hosted application is served at the root of a domain).

so for the question asked above:

.app-header {
  background-color: #222;
  height: 150px;
  padding: 20px;
  color: white;
  background-image: url("/example.png");
}

the critical part being

/example.png 

refers to a file, example.png, that is in the public folder (served at the root level)

could also be relative:

one could also use

./example.png

provided that the css file was also imported from the public/build directory, this would be relative to the css file and not depend on being served at the domain root, but typically in cra webpack will bundle the css and it may or may not be loaded from this location. (you could import it in the html file directly using rel tag with the %public_url%/styles.css macro)

score:0

remove the extra .. in the relative path. :)

score:0

use "./image.png".

the logic behind is that the css file you will place the code in, will be part of index.html when the app is finished, built and deployed.

score:0

the only way that helped me is adding full url-adress to the image path. so this one can help:

background-image: url("http://localhost:3000/background.jpg"); 

score:0

background-image: url("http:/images/pexels-photo-1.jpg");

score:1

there is a special page about the /public folder in the official documentation:
https://create-react-app.dev/docs/using-the-public-folder/

here is how you should refer to the public folder:

<link rel="icon" href="%public_url%/favicon.ico" />

or

render() {
  return <img src={process.env.public_url + '/img/logo.png'} />;
}

but, you can't use those solution in a css file. so you'll have to precise the ressource from the js files:

const mycomp = () => {
  return <div style={{ backgroundimage: `${process.env.public_url}/img/logo.png` }} />;
}

score:1

i was using "public" folder but it says here to use images inside "src" folder:

https://create-react-app.dev/docs/using-the-public-folder/

"normally we recommend importing stylesheets, images, and fonts from javascript."

score:3

in my case, to access the images from css/scss, had to move the images directory as well as fonts, to the src directory. after which i was able to refer them in the css/scss files directly,

 background-image: url("/images/background.jpg");

references:

https://github.com/facebook/create-react-app/issues/829

https://create-react-app.dev/docs/using-the-public-folder/


Related Query

More Query from same tag