Where developers come to connect, share, build and be inspired.


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.


  • 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!

  • D2a1c95e2af59538301c3ee6d2907f6f

    What about the default http_path option ?

Add a comment