exj0ig
15.6K
· November 2012 ·
6b4b7f11163b1e87571995ce8c3f0bce

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.

Sign in or sign up to add your response.

2 Responses

1694
13027845faeb65d26acd203f755ceb21

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 ·
1708
D2a1c95e2af59538301c3ee6d2907f6f

What about the default http_path option ?

over 1 year ago ·