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
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');
3 Comments
AbdulAziz
Thank you for the detailed answer. I was really confused in the same issue, and here you just solved it in a better way.
Davide
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.Suleman
Why is the brace not closed for div in styles.css ?
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:
1 Comment
Jakob Alexander Eichler
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
Yes, it's relative to the stylesheet. See MDN for up-to-date references; right now, the latest draft is [css-values-4].