Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reference CSS background images in production in Rails 4.0?

I switched an app over from 3.2.12 to 4.0.0.rc1. When I viewed it in production afterwards, the background image had disappeared. The rest of my image assets were fetched with no problem.

In my logs, I saw that all the successfully rendered images had a digest tacked to the end of them, like so:

2013-05-12T19:57:05.856277+00:00 heroku[router]: at=info method=GET path=/asset/explore-9ec2a1cfd4784133755637f6ef6d5673.png host=xxx.herokuapp.com fwd="69.140.148.75" dyno=web.1 connect=3ms service=5ms status=200 bytes=4064

And my unsuccessful background image had no digest on it, plus a 404 response code:

2013-05-12T19:57:05.736354+00:00 heroku[router]: at=info method=GET path=/assets/background.png host=xxxx.herokuapp.com fwd="69.140.148.75" dyno=web.1 connect=2ms service=7ms status=404 bytes=728

In the production.rb file, there's a config line that enables this for caching purposes:

# Generate digests for assets URLs
config.assets.digest = true

This is the CSS for the background:

body {
  background-image: url('background.png');
  background-attachment: fixed;
  background-position: 100% 100%;
  background-repeat: no-repeat;
}

I concluded that my CSS file was trying to fetch an image url that didn't exist, because it was referencing the plain asset ("background.png") without the hash at the end. This is only an issue for images in the CSS; all images referenced in my .erb files are fine. So how do I reference this asset in my CSS without hardcoding the digest in? Are there any workarounds?

Thanks for reading.

like image 337
hlh Avatar asked May 12 '13 21:05

hlh


People also ask

Which of the CSS property is used to set the background image of an element?

The background-image CSS property sets one or more background images on an element.

How do you specify an image for the background of an element?

One way is to use the background-image CSS property. This property applies one or more background images to an element, like a <div> , as the documentation explains.

How do you put a background image in CSS stylesheet?

By default, a background-image is placed at the top-left corner of an element, and repeated both vertically and horizontally. Tip: The background of an element is the total size of the element, including padding and border (but not the margin). Tip: Always set a background-color to be used if the image is unavailable.


1 Answers

Use asset-url. Rails will preprocess this and expand the proper url.

body {
  background-image: asset-url('background.png');
  background-attachment: fixed;
  background-position: 100% 100%;
  background-repeat: no-repeat;
}
like image 64
aromero Avatar answered Nov 07 '22 07:11

aromero