Is a Relative Path in a CSS File Relative to the CSS File

Is a relative path in a CSS file relative to the CSS file?

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');

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.

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.

Relative path to CSS file?

From the API

If $path is prefixed with '/', the path will be relative to the webroot of your application. Otherwise, the path will be relative to your CSS path

So you could start the path with a / and then point from there, that way you don't need to go backwards in directories.

Credit to this answer for pointing this out

Relative path in a HTML file

What is the web application root depends on your server configuration.

As an alternative you can use:

<link rel="stylesheet" type="text/css" href="../../templates/css/main-style.css">

How to use relative/absolute paths in css URLs?

The URL is relative to the location of the CSS file, so this should work for you:

url('../../images/image.jpg')

The relative URL goes two folders back, and then to the images folder - it should work for both cases, as long as the structure is the same.

From https://www.w3.org/TR/CSS1/#url:

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



Related Topics



Leave a reply



Submit