Rails: How to set a background image in rails from css?

后端 未结 14 1370
太阳男子
太阳男子 2020-12-08 06:01

I am using rails 3.2 and i have to set a background for one of the page and i have tried many ways and nothing went right, so looking for some good help. I have tried

相关标签:
14条回答
  • 2020-12-08 07:02

    Lots of answers for this one, figured I'd throw in my solution, which addresses the original question, since they were originally attempting to use, among other things, an ERB helper:

    following the link from above from Kangkyu, I learned it's possible to add the .erb file extension onto my .css file. Which is definitely what Kangkyu did.

    application.css.erb

    This gives me access to the helper methods.

    Instead of fussing with figuring out the correct path to the image, I used:

    <%= asset_path "image_name.png" %>
    

    so my CSS property/value pair looks like this:

    background-image: url(<%= asset_path 'foo.jpg' %>);
    
    0 讨论(0)
  • 2020-12-08 07:02

    I had this challenge when working on a rails 6 application.

    Here's how I fixed it:

    For an image located in app/assets/images/my-image.jpg, assuming that it is a CSS background image, you should reference this way:

    background-image: url(<%= /assets/my-image.jpg' %>)
    

    For an image located in app/assets/images/slides/my-slide.jpg, assuming that it is a CSS background image, you should reference this way:

    background-image: url(<%= asset_path 'slides/my-slide.jpg' %>)
    

    Note: This worked well in development and production environments

    You can read up more on this in the official Rails Documentation: Coding Links to Assets

    That's all.

    I hope this helps

    0 讨论(0)
提交回复
热议问题