How to get absolute image paths in your css files using sass/scss
When using sass-rails you get a helper called image-url
which you can use instead of url
in your .scss
files. Something like:
body {
background-image: image-url(background.png);
}
which will parse into something like:
body {
background-image: url(/assets/background.png);
}
This should be common knowledge, but it is relative, so how to get this url absolute? Simply set the asset_host
config on the action_controller
.
The trick:
config.action_controller.asset_host = "http://your.domain.com/"
Then your css will look something like that:
body {
background-image: url(http://your.domain.com/assets/background.png);
}
But beware this will also trigger the asset_path
helper to return absolute urls as well, but chances are very high, that if you want absolute urls in the css you also want it everywhere.
Written by Georg
Related protips
2 Responses
If the asset_path is an issue, you can define a custom function for the images to work around it (although this removes the ability to configure with config.rb):
@function remote-image-url($name) {
@return unquote("url(http://your.domain.com" + image-url($path) + ")");
}
Then just call remote-image-url instead of image-url when you want the path in there!
What about the default http_path option ?