How to use relative/absolute paths in css URLs?

CssRelative PathAbsolute Path

Css Problem Overview


I have a production and development server. The problem is the directory structure.

Development:

  • http://dev.com/subdir/images/image.jpg
  • http://dev.com/subdir/resources/css/style.css

Production:

  • http://live.com/images/image.jpg
  • http://live.com/resources/css/style.css

How can I have a style.css in css folder that uses on both servers the same path for the background: url property? Is there a trick I can use with relative paths?

Css Solutions


Solution 1 - Css

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

Solution 2 - Css

Personally, I would fix this in the .htaccess file. You should have access to that.

Define your CSS URL as such:

url(/image_dir/image.png);

In your .htacess file, put:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^image_dir/(.*) subdir/images/$1

or

RewriteRule ^image_dir/(.*) images/$1

depending on the site.

Solution 3 - Css

i had the same problem... every time that i wanted to publish my css.. I had to make a search/replace.. and relative path wouldnt work either for me because the relative paths were different from dev to production.

Finally was tired of doing the search/replace and I created a dynamic css, (e.g. www.mysite.com/css.php) it's the same but now i could use my php constants in the css. somethig like

.icon{
  background-image:url('<?php echo BASE_IMAGE;?>icon.png');
}

and it's not a bad idea to make it dynamic because now i could compress it using YUI compressor without loosing the original format on my dev server.

Good Luck!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjohnlemonView Question on Stackoverflow
Solution 1 - CssKobiView Answer on Stackoverflow
Solution 2 - CssGarison PiattView Answer on Stackoverflow
Solution 3 - CsspleasedontbelongView Answer on Stackoverflow