How to reference images in CSS within Rails 4

2020-01-23 04:26发布

There's a strange issue with Rails 4 on Heroku. When images are compiled they have hashes added to them, yet the reference to those files from within CSS don't have the proper name adjusted. Here's what I mean. I have a file called logo.png. Yet when it shows up on heroku it is viewed as:

/assets/logo-200a00a193ed5e297bb09ddd96afb953.png

However the CSS still states:

background-image:url("./logo.png");

The result: the image doesn't display. Anybody run into this? How can this be resolved?

17条回答
祖国的老花朵
2楼-- · 2020-01-23 04:52

This should get you there every single time.

background-image: url(<%= asset_data_uri 'transparent_2x2.png'%>);
查看更多
姐就是有狂的资本
3楼-- · 2020-01-23 04:53

WHAT I HAVE FOUND AFTER HOURS OF MUCKING WITH THIS:

WORKS :

background-image: url(image_path('transparent_2x2.png')); 

// how to add attributes like repeat, center, fixed?

The above outputs something like: "/assets/transparent_2x2-ec47061dbe4fb88d51ae1e7f41a146db.png"

Notice the leading "/", and it's within quotes. Also note the scss extension and image_path helper in yourstylesheet.css.scss. The image is in the app/assets/images directory.

Doesn't work:

background: url(image_path('transparent_2x2.png') repeat center center fixed;

doesn't work, invalid property:

background:url(/assets/pretty_photo/default/sprite.png) 2px 1px repeat center fixed;

My last resort was going to be to put these in my public s3 bucket and load from there, but finally got something going.

查看更多
做自己的国王
4楼-- · 2020-01-23 04:55

In css

background: url("/assets/banner.jpg");

although the original path is /assets/images/banner.jpg, by convention you have to add just /assets/ in the url method

查看更多
聊天终结者
5楼-- · 2020-01-23 04:55

By default Rails 4 will not serve your assets. To enable this functionality you need to go into config/application.rb and add this line:

config.serve_static_assets = true

https://devcenter.heroku.com/articles/rails-4-asset-pipeline#serve-assets

查看更多
Evening l夕情丶
6楼-- · 2020-01-23 04:55

In Rails 4, simply use

.hero { background-image: url("picture.jpg"); }

in your style.css file as long as the background image is tucked in app/assets/images.

查看更多
登录 后发表回答