I am using the html5 boilerplate layout which has a css, img, and js directory at the same level. I am having all kinds of issues accessing images from my .css files and .js files. I have been warned that using ../ may cause problems, but without some kind of url generator (like I have with my template files), how can I best access images from my .js and .css files?

有帮助吗?

解决方案

One robust way to access static resources in CSS is to always give the full path:

body {
    background-image: url("/path/to/image.png");
}

Notice the preceding / character. It tells the browser to look for the file at the root of the server. For example, if you currently are on http://example.com/pictures/album/5 then the above CSS will find the background at http://example.com/path/to/image.png.

Using the full path also encourages you to keep your resources well organized.

This is not to say that using relative paths is a bad thing, though. If you are working on a CSS project and put it in a sub-folder, say /static/myproject/project.css, then you can refer to images in that folder using relative paths.

If we say that your project is at /static/myproject, and the folder structure looks like this:

/static/myproject/project.css
/static/myproject/back-button.gif
/static/myproject/forward-button.gif

Then, in your CSS file, you can call the images relative to the CSS file:

.back {
    background-image: url("back-button.gif");
}
.forward {
    background-image: url("forward-button.gif");
}

The problem with doing it like this is that resources tend to be stored all over the place. That makes it more difficult to reuse resources.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top