ndvo
ndvo

Reputation: 989

Is it possible to reference an image in HTML file folder from CSS?

I'm aware CSS relative paths while referencing images are relative to the CSS file itself. I want to reference an image in the HTML file folder, so that though the image will always have the same name, there will be a different image fore each directory visited.

I have a directory structure similar to this:

book/
-index.html
-style.css
-chapter1/
--background.png
--index.html
-chapter2/
--index.html
--background.png

I want the style.css to reference the background.png image of each index.html as the background.png that is in the same directory of the relevant index.html.

Is that possible? If so, how can I do it.

Upvotes: 0

Views: 672

Answers (1)

GolezTrol
GolezTrol

Reputation: 116100

This is not possible in an external style sheet. Image urls are relative to the style sheet url, not the document url.

You can solve this by adding the CSS to the document itself. You don't need the entire CSS in the document, but you could just add the background image in the document:

<style>.yourclass{ background-image: url('background.png'); }</style>

It's not great, but I think it's the best solution at this moment.

Alternatively, you can specify the backgrounds for all documents in the css and add a class to the document. For instance, you can add the document title as a class to the body, and base your style on that, so you would get something like

body.chapter-1 .yourclass{ background-image: url('../chapter1/background.png'); }

The disadvantage, of course, is that you would have to know the documents and add each one to the style sheet. So it depends on your situation which one works best. If you want your chapters to choose from a select number of styles, adding a class would be the best option. If each document should have its own background, I think embedding it in the document itself would be the best option, otherwise your stylesheet will contain your complete website index and has to be changed every time you add new content.

Upvotes: 2

Related Questions