78

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?

4 Answers 4

90

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');
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the detailed answer. I was really confused in the same issue, and here you just solved it in a better way.
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.
Why is the brace not closed for div in styles.css ?
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

1 Comment

The include from an external domain will only work in some browsers if you have set the header to allow external includes, due to the same origin policy
1

To the CSS file.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.