Reference file in public folder from CSS in create-react-app

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/


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)


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` }} />;
}