Last Updated: April 13, 2020
·
40.47K
· calamari

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 urlin 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.

2 Responses
Add your response

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!

over 1 year ago ·

What about the default http_path option ?

over 1 year ago ·