77

When I reference an image or other file in a CSS file by a relative path, is the path relative to the CSS file or the HTML file using the CSS file?

Nathan Osman
  • 71,149
  • 71
  • 256
  • 361

4 Answers4

89

Yes, it's relative to the .css

Here's an example layout:

Page:  page.htm ... does not matter where
CSS:   /resources/css/styles.css  
Image: /resources/images/image.jpg

CSS in styles.css:

div { background-image: url('../images/image.jpg');
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • Thank you for the detailed answer. I was really confused in the same issue, and here you just solved it in a better way. – AbdulAziz Feb 28 '12 at 13:45
  • 4
    This is indeed reasonable, because it allows referencing the _same_ `.css` file from different `.html` files (which may be located in different places) without braking paths to external objects. – Davide Mar 04 '14 at 14:06
  • 1
    Why is the brace not closed for div in styles.css ? – Suleman Oct 12 '19 at 07:18
9

Yes. It is relative to the CSS file. I'll add that this also includes relative to the domain the CSS file is on.

So if the CSS is referenced as:

<link href="http://www.otherdomain.com/css/example.css" type="text/css" rel="stylesheet" />

and it contains:

div { background-image: url('/images/image.jpg');

The background will be:

http://www.otherdomain.com/images/image.jpg

jshoaf
  • 133
  • 1
  • 4
1

To the CSS file.

empz
  • 11,509
  • 16
  • 65
  • 106
1

Yes, it's relative to the stylesheet. See MDN for up-to-date references; right now, the latest draft is [css-values-4].

SamB
  • 9,039
  • 5
  • 49
  • 56