Wais Kamal
Wais Kamal

Reputation: 6210

How do I use relative filepaths for an image in a different folder from my CSS file?

I have a web page with the following folder structure:

MyWebpage
  - css
    - layout.css
  - img
    - wallpaper.jpg
  - js
  - index.html

I have the following line included in index.html

<link rel="stylesheet" type="text/css" href="css/layout.css">

Now, I want to use the image wallpaper.jpg as the background for the <body> element. How can I use relative referencing here? Should I locate the file relative to the CSS file, like this,

body {
  background: url('../img/wallpaper.jpg');
}

or relative to the HTML file, like this?

body {
  background: url('img/wallpaper.jpg');
}

Upvotes: 0

Views: 47

Answers (1)

Payal2299
Payal2299

Reputation: 148

It really depends on where you are writing your CSS.

If you are writing an inline style or using <head> <style> tags in the HTML file, then use a path relative to the HTML file (../ in this case), as you are telling browser to load the image from the HTML file.

And if you are writing the style in the CSS file, the style is relative to the CSS file destination (no ../ in this case), as you will load the CSS file from the HTML file and the CSS file will load all the required resources.

Upvotes: 2

Related Questions