Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background image url() works on live server but when I open the index.html in the browser it doesn't?

Tags:

html

css

sass

The element is selected properly because other properties apply. There are no console errors.

I have tried:

  1. img/hero.jpg - works when I click on link in VS Code
  2. /img/hero.jpg - works when I click
  3. ../../hero.jpg - work when I click
  4. ../img/hero.jpg - doesn't work
  5. the full path - works when I click

The problem is seen here. You can see that images called by the src attribute work.

Here is the file structure.

like image 221
NaniSore Avatar asked Jan 26 '26 16:01

NaniSore


1 Answers

I honestly don't understand your setup / question, but I think if you understand how relative URLs work a little better you can figure it out yourself.

On your server you have your files in somewhere like,

/var/www/html/index.html
/var/www/html/css/styles.css
/var/www/html/img/background.png

On your computer you have your files somewhere like,

C:\Users\Nani\Desktop\Website\index.html
C:\Users\Nani\Desktop\Website\css\styles.css
C:\Users\Nani\Desktop\Website\img\background.png

And in your styles.css you have something like this,

body {
    background-image: url('/img/background.png');
}

Starting the URL with / tells the browser to interpret it as the root directory. On a Windows PC it will be C:\ and on a Linux PC it'll be /.

However, when you access the page once it is online from a url like https://example.com, the root directory becomes https://example.com/.

Therefore, using /img/background.png will make it look for the image at https://example.com/img/background.png once it is online, but on your local machine it'll be looking for the image at C:\img\background.png

Starting the url without the slash like this, img/background.png looks for the image relative to the folder that the css file is in. So in that case online it'll look for the background here at https://example.com/css/img/background.png and on your local machine it'll look in C:\Users\Nani\Desktop\Website\css\img\background.png

In my example, the best solution would be to use ../img/background.png, that'll look up one directory relative to the css folder, and then in the img folder. That'll work consistently on both your own computer and once it is uploaded.

That should be enough to figure out what you need to do assuming that the problem is the way the url path is declared. Otherwise, the problem might be with something else. For example, it seems like you're using SCSS. Perhaps the SCSS isn't compiled on your local machine (or hasn't been in a while), but it is compiled on the live server?

like image 193
Michael Avatar answered Jan 29 '26 08:01

Michael