CSS Relative Url to Images

Using relative URL in CSS file, what location is it relative to?

According to W3:

Partial URLs are interpreted relative to the source of the style sheet, not relative to the document

Therefore, in answer to your question, it will be relative to /stylesheets/.

If you think about this, this makes sense, since the CSS file could be added to pages in different directories, so standardising it to the CSS file means that the URLs will work wherever the stylesheets are linked.

CSS relative url to images

With the directory tree you are providing you don't have to change your path.

.. means the parent directory of the CSS file so the assets/ directory is implied.

background-image relative url doesnt work in CSS stylesheet

url() in CSS is relative to the location of your CSS file.

If I understand you correctly, this is your folder structure:

-+-img
| +--images
+html_file
+css_file

If so, try this:

#Philippines {
background-image:url("img/UK.png");
}

Solution to relative path to image in CSS file depending on what file that includes it

The only way is with absolute paths. This means that in your CSS you must define an absolute path for your images, for example:

 background-image: url(/images/image.png);

What's the problem? You need to know the absolute path where your folders are. For example, if you have this URL: http://localhost/myFolder/images/image.png, your CSS will be:

 background-image: url(/myFolder/images/image.png);

But when you upload it to a production server like this: http://myserver.com/images/image.png, your CSS must to change to something like this:

 background-image: url(/images/image.png);

So the best way is to develop in the same environment that your production server. This will be with the URL http://localhost/images/image.png (develop) and http://myserver.com/images/image.png (production).

Another way is to making friendly URLs, that avoids to you to make custom folders, and you can have all in one folder and the URLs will be rewrited by the server.

Good luck.



Related Topics



Leave a reply



Submit