-1

I'm trying to display a background-image using html/css, but it only seems to show up if I put the image in certain folders.

I have an image at project/assets/background.png and I'm trying to access it from project/src/css/style.css. I tried this

background-image: url('../../assets/background.png');

but it didn't work. The spelling and path should be correct because I used vscode's autocomplete. So, I copied the image file into all the intermediate directories along the file path and tested them:

background-image: url('background.png');
background-image: url('../background.png');
background-image: url('../../background.png');

These all worked. But it seems like any path that goes into a directory doesn't work:

background-image: url('../../folder/background.png');

Does anyone have an idea why this happens?

This is my first time posting. Please tell me if I can be clearer. Thanks.

  • What do you see the network tab of your browser's inspector when it tries to fetch the image? Do you see a 404 error? – Brett Donald May 03 '23 at 23:16
  • Hi, I didn't see any errors. The image just wouldn't show up. I think it's works fine now. I opened the project directory on vscode instead of just src directory. I was using vscode live server so maybe that's why it didn't work? Thanks anyways. – stuckoverflow May 04 '23 at 00:36

1 Answers1

1

Assuming you have the same file structure as in the attached image to the answer, you can see that my image is in the assets folder with the name loading.gif.

So, if you are using VS code, then just by typing background-image:url("/") you will see that VS code gives you some suggestions. One of the suggestions will be assets/ and this is where my image is stored. You will see that the final path for me would be url("/assets/loading.gif).

Also, the following link might be helpful to you.

How to give the background-image path in CSS?.

Hope it helps!

enter image description here

Rob
  • 14,746
  • 28
  • 47
  • 65
  • Sorry, to clarify, my css file is at `project/src/css/style.css` and I'm trying to access `project/assets/background.png`. I think the correct path would be `../../assets/background.png` but it doesn't work. I tried moving style.css out to match your example but that didn't work either. Any help would be appreciated. – stuckoverflow May 03 '23 at 22:44
  • Yes, you are right, that should be the path, which means something else might be wrong. Can you confirm whether the link tag in your html file has the right path? I think it should be ``. – Shaswat_Shukla May 04 '23 at 07:47